import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class TestLinuxIP {
public static void main(String[] args) {
//test1();
test2();
}
private static void test1() {
InetAddress inet;
try {
inet = InetAddress.getLocalHost();
String ipAddress = inet.getHostAddress();
System.out.println(ipAddress);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void test2(){
//根据网卡取本机配置的IP
Enumeration netInterfaces;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while(netInterfaces.hasMoreElements()){
NetworkInterface ni=(NetworkInterface)netInterfaces.nextElement();
System.out.println(ni.getName());
ip=(InetAddress) ni.getInetAddresses().nextElement();
if( !ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":")==-1){
System.out.println("本机的ip=" + ip.getHostAddress());
break;
} else {
ip=null;
}
}
System.out.println("~~~~~" + ip.getHostAddress());
} catch (SocketException e) {
e.printStackTrace();
}
}
}