天天看點

java擷取真實ip_java 擷取用戶端真實ip

public static String getLocalRealIP(){

String ip = "";

//try {

//InetAddress addr = InetAddress.getLocalHost();

//ip=addr.getHostAddress().toString();

//System.out.println(ip);

//} catch (UnknownHostException e) {

//System.out.println("擷取本機ip失敗");

//e.printStackTrace();

//}

try {

Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();

InetAddress inetAddress = null;

while (netInterfaces.hasMoreElements()) {

NetworkInterface ni = (NetworkInterface) netInterfaces

.nextElement();

//                System.out.println("---Name---:" + ni.getName());

Enumeration nii = ni.getInetAddresses();

while (nii.hasMoreElements()) {

inetAddress = (InetAddress) nii.nextElement();

if (inetAddress.getHostAddress().indexOf("192.168.") != -1) {

ip=inetAddress.getHostAddress();

}

}

}

} catch (SocketException e) {

e.printStackTrace();

}

return ip;

}