public class NetInfo {
public static void main(String[] args) {
new NetInfo().say();
}
public void say() {
try {
java.net.InetAddress i = java.net.InetAddress.getLocalHost();
System.out.println(i); // name and IP address
System.out.println(i.getHostName()); // name
System.out.println(i.getHostAddress()); // IP address only
}
catch(Exception e){e.printStackTrace();}
}
}
> java NetInfo realone/209.142.72.112 realone 209.142.72.112
To list all the interfaces available on a workstation :
[JDK1.4]
import java.net.*;
import java.util.*;
import java.io.*;
import java.nio.*;
public class IPAdress {
public void getInterfaces (){
try {
Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements()) {
NetworkInterface netface = (NetworkInterface)
e.nextElement();
System.out.println("Net interface: "+netface.getName());
Enumeration e2 = netface.getInetAddresses();
while (e2.hasMoreElements()){
InetAddress ip = (InetAddress) e2.nextElement();
System.out.println("IP address: "+ip.toString());
}
}
}
catch (Exception e) {
System.out.println ("e: " + e);
}
}
public static void main(String[] args) {
IPAdress ip = new IPAdress();
ip.getInterfaces();
}
}> java IPAdress Net interface: lo IP address: /127.0.0.1 Net interface: eth0 IP address: /194.168.0.1 Net interface: eth1 IP address: /164.254.147.20 Net interface: ppp0 IP address: /64.68.115.69
A "low-tech" way to get the computer name (can be useful if there is no network card) is to use the environment variable COMPUTERNAME (at least on modern Windows installation).
So pass it to your JVM as java -Dcomputername="%COMPUTERNAME%" ... and the get the value with System.getProperty("computername") or use the jdk1.5 which can extract environment variable directly with System.getenv("COMPUTERNAME")
Written and compiled by Réal Gagnon ©1998-2005
[ home ]