有时候
InetAddress.getLocalHost().getHostAddress()
会因为本机网络环境发生变化出问题,用下面方法可以获得本机所有IP。
EXample:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetIPAddressOuterExample {
/**
* @param args
* @throws SocketException
*/
public static void main(String[] args) throws SocketException {
// TODO Auto-generated method stub
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements())
{
Enumeration<InetAddress> l = e.nextElement().getInetAddresses();
while (l.hasMoreElements())
{
System.out.println(l.nextElement().getHostAddress());
}
}
}
}
Result:
@CacheTechShare