星期三, 十月 28, 2009

Java中如何得到网卡的IP地址而不是127.0.0.1

tip:最后发现,如果是web程序可以通过,javax.servlet.http .HttpServletRequest里的:getServerName()可以用来得到外部IP,很奇怪。getLocalAddr().getHostAddress()的结果不同.


String ipaddress="";
java.util.Enumeration interfaces = java.net.NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements())
{
java.net.NetworkInterface card = (java.net.NetworkInterface) interfaces.nextElement();
java.util.Enumeration addresses = card.getInetAddresses();
if (addresses == null)
continue;

while (addresses.hasMoreElements())
{
java.net.InetAddress address = (java.net.InetAddress) addresses.nextElement();
if(!address.isLoopbackAddress())//skip 127.0.0.1 address
{
if(address.isSiteLocalAddress())//yes,it,not NIC link address
{
ipaddress=address.getHostAddress();
break;
}
}
}
}