1.方法
public static void main(String[] args) {
String ip="";
InetAddress inetAddress = null;
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while (nias.hasMoreElements()) {
InetAddress ia = (InetAddress) nias.nextElement();
if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
inetAddress=ia;
ip=inetAddress.getHostAddress();
}
}
}
if (null!=inetAddress){
System.out.println(inetAddress.getHostAddress());
System.out.println(inetAddress.getHostName());
System.out.println(inetAddress.getCanonicalHostName());
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("程序所运行服务器的ip:"+ip);
}