Javascript is required

Javaweb获取本地IP地址和客户端IP地址

作者: IP数据云

栏目: 技术解读

发布时间: 2022-10-11 15:48:10

1、获取本地地址


public static InetAddress getLocalHostLANAddress() {

try {

InetAddress candidateAddress = null;

// 遍历所有的网络接口

for (Enumeration<NetworkInterface> ifaces =

NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {

NetworkInterface iface = (NetworkInterface) ifaces.nextElement();

// 在所有的接口下再遍历IP

for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {

InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();

System.out.println(inetAddr.getHostAddress() + "," + inetAddr.getHostName() + "," + inetAddr);

if (!

inetAddr.isLoopbackAddress()) {// 排除loopback类型地址,即本地测试地址,像127.0.0.1 localhost

if (

inetAddr.isSiteLocalAddress()) {

// 如果是site-local地址,就是它了

return inetAddr;

} else if (candidateAddress == null) {

// site-local类型的地址未被发现,先记录候选地址

candidateAddress = inetAddr;

}

}

}

}

if (candidateAddress != null) {

return candidateAddress;

}

// 如果没有发现 non-loopback地址.只能用最次选的方案

InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();

return jdkSuppliedAddress;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}



2、获取 mac 地址


public static String getLocalMac(InetAddress ia) {

// TODO Auto-generated method stub

//获取网卡,再解析地址

byte[] mac = new byte[0];

try {

//获取到的mac地址的字节数组,要解析成16进制

mac =

NetworkInterface.getByInetAddress(ia).getHardwareAddress();

} catch (SocketException e) {

e.printStackTrace();

}

//System.out.println("mac数组长度:"+mac.length);

StringBuffer sb = new StringBuffer("");

for(int i = 0; i < mac.length; i++) {

if (i != 0) {

sb.append("-");

}

//字节转换为整数

int temp = mac[i] & 0xff;

String str = Integer.toHexString(temp);

//System.out.println("每8位:"+str);

if (str.length() == 1) {

sb.append("0" + str);

} else {

sb.append(str);

}

}

return sb.toString();

}


3、获取客户端的 IP


public static String getRealIp(HttpServletRequest request) {

String ip = null;

try {

ip = request.getHeader("X-FORWARDED-FOR ");

if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {

ip = request.getHeader("Proxy-Client-IP");

}

if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {

ip = request.getHeader("WL-Proxy-Client-IP");

}

if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {

ip = request.getHeader("HTTP_CLIENT_IP");

}

if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {

ip = request.getHeader("X-Real-IP");

}

if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {

ip = request.getRemoteAddr ();

}

if (ip != null && ip.contains(",")) {

ip = ip.split(",")[0];

}

} catch (Throwable e) {

}

return ip;

}


IP地址查询,通过IP数据云 - 免费IP地址查询


IP数据云利用大数据挖掘和网络空间地图测绘技术与人工智能(AI)算法相结合,利用动态密度聚类算法和基于多层神经网络的IP地址定位算法,完成IP地址地理位置定位。IP数据云接口响应快,多台服务器构建 API 接口负载均衡。IP数据云利用全球超700个网络监测点辅助测量,IP地址查询定位准确度超过99.8%。