代码:
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class testGetIp {
public static void main(String[] args) {
InetAddress ip = null;
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
//排除虚拟接口和没有启动运行的接口
if (netInterface.isVirtual() || !netInterface.isUp() || netInterface.isLoopback() || netInterface.isPointToPoint()) {
continue;
} else {
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if ((ip instanceof Inet4Address)) {
System.out.println("IP 地址:"+ip.getHostAddress());
return ;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ;
}
}