Java获得Linux/opensolaris 主网卡IP

来源:百度知道 编辑:UC知道 时间:2024/06/05 06:47:06
Opensolaris或则LINUX下安装有多张网卡(1张主网卡和其余5张其他网卡),

主网卡Ip; 172.16.80.25
其余网卡IP: 192.168.223.45
192.168.223.66 等等
使用如下代码:
String localip="";
Enumeration netInterfaces=NetworkInterface.getNetworkInterfaces();
InetAddress mylocalip = null;
while(netInterfaces.hasMoreElements()){
NetworkInterface ni=(NetworkInterface)netInterfaces.nextElement();
System.out.println(ni.getName());
mylocalip=(InetAddress) ni.getInetAddresses().nextElement();
if( !mylocalip.isLoopbackAddress() && mylocalip.getHostAddress().indexOf(":")==-1) {
localip = mylocalip.getHostAddress();
break;
}else{
mylocalip=null;
}
}

可以获取到网卡的IP地址,但是副网卡的IP地址192.168.223.45。而不是主网卡的IP地址 172.16.80.73<

netInterfaces是一个包含所有网络端口的enumeration,其中端口顺序不保证,你方法里只取到了第一个不是本地回送端口的端口就break了,但这端口不一定是你想要的主网卡ip。要获得你想要的ip地址,试试InetAddress.getByName("xxx"),xxx是你机器的完整计算机名称。