谁清楚java代码获取ip地址方法是什么

Python014

谁清楚java代码获取ip地址方法是什么,第1张

1、如果服务器如果没有采用反向代理,而且客户端没有用正向代理的话,那么可以获取客户端的真实IP地址request.getRemoteAddr()

2、如果服务器如果没有采用反向代理,而且客户端有用正向代理的话,那么通过request.getRemoteAddr()获取客户端的IP地址是客户端 的代理服务器的地址,并不是客户端的真实地址

3、如果客户端使用的是多层代理的话,服务器获得的客户端地址是客户端的最外围代理服务器的地址如果服务器如果采用反向代理服务器,不管客户端采用的是何种方式访问服务器

import java.net.Inet4Address

import java.net.InetAddress

import java.net.NetworkInterface

import java.net.SocketException

import java.util.ArrayList

import java.util.Enumeration

import java.util.List

/**

* @author Becolette

* @description TODO

* @date 2015-11-5 下午01:58:46

*/

public class IpAddress {

public static String find() {

List<String>ips = new ArrayList<String>()

// 返回所有网络接口的一个枚举实例

Enumeration<?>allNetInterfaces = null

try {

allNetInterfaces = NetworkInterface.getNetworkInterfaces()

} catch (SocketException e) {

e.printStackTrace()

}

InetAddress ip = null

while (allNetInterfaces.hasMoreElements()) {

NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement()

Enumeration<InetAddress>addresses = netInterface.getInetAddresses()

while (addresses.hasMoreElements()) {

// 获得当前网络接口

ip = (InetAddress) addresses.nextElement()

if (ip != null &&ip instanceof Inet4Address &&ip.getHostAddress().indexOf(".") != -1) {

ips.add(ip.getHostAddress())

}

}

}

if (ips.size() == 1) {

return ips.get(0)

} else {

for (String ipa : ips) {

if (!"127.0.0.1".equals(ipa)) {

return ipa

}

}

}

return MacAddress.find()

}

}