获取真实用户IP地址
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetLocalIPAddress {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
String ipAddress = localHost.getHostAddress();
System.out.println("本地机器的 IP 地址是:" + ipAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetRealIPAddress {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
String ipAddress = inetAddress.getHostAddress();
System.out.println("真实的 IP 地址是:" + ipAddress);
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}