这个问题以前的blog上写过, 可我怎么也找不到了. 反正当时的方法是有问题的, 正好在这里重新写一遍. 以前用的方法是:
public String getLocalIP() {
try {
java.net.InetAddress inet = java.net.InetAddress.getLocalHost();
return inet.getHostAddress();
} catch (java.net.UnknownHostException ex) {
return null;
}
}
这个方法的缺陷是在Linux系统上Java读的是配置/etc/hosts里的内容, 如果用户自己修改了该文件的内容, 此方法无法正确使用.
新的方法则避免了读取配置文件, 此方法在Windows, Linux, Mac OS X下均调试通过.
public String getLocalIP()
{
Enumeration e1 = (Enumeration) NetworkInterface.getNetworkInterfaces();
while(e1.hasMoreElements())
{
NetworkInterface ni = (NetworkInterface) e1.nextElement();
System.out.print(ni.getName());
System.out.print(": ");
Enumeration e2 = ni.getInetAddresses();
while(e2.hasMoreElements())
{
InetAddress ia = (InetAddress) e2.nextElement();
if (ia instanceof Inet6Address) continue; //omit IPv6 address
System.out.print(ia.getHostAddress());
if(e2.hasMoreElements())
{
System.out.print(", ");
}
}
System.out.print("\n");
}
}
public String getLocalIP() {
try {
java.net.InetAddress inet = java.net.InetAddress.getLocalHost();
return inet.getHostAddress();
} catch (java.net.UnknownHostException ex) {
return null;
}
}
这个方法的缺陷是在Linux系统上Java读的是配置/etc/hosts里的内容, 如果用户自己修改了该文件的内容, 此方法无法正确使用.
新的方法则避免了读取配置文件, 此方法在Windows, Linux, Mac OS X下均调试通过.
public String getLocalIP()
{
Enumeration e1 = (Enumeration) NetworkInterface.getNetworkInterfaces();
while(e1.hasMoreElements())
{
NetworkInterface ni = (NetworkInterface) e1.nextElement();
System.out.print(ni.getName());
System.out.print(": ");
Enumeration e2 = ni.getInetAddresses();
while(e2.hasMoreElements())
{
InetAddress ia = (InetAddress) e2.nextElement();
if (ia instanceof Inet6Address) continue; //omit IPv6 address
System.out.print(ia.getHostAddress());
if(e2.hasMoreElements())
{
System.out.print(", ");
}
}
System.out.print("\n");
}
}
回复Comments
作者:
{commentrecontent}