1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java 获取客户端真实 ip 地址和 mac 地址

java 获取客户端真实 ip 地址和 mac 地址

时间:2021-05-16 01:50:30

相关推荐

java 获取客户端真实 ip 地址和 mac 地址

现在都流行显示 ip 归属地,那么我先来获取客户端的真实 ip 地址以及 mac 地址,上代码

import javax.servlet.http.HttpServletRequest;import .InetAddress;import workInterface;import .UnknownHostException;/*** 常用获取客户端信息的工具*/public class NetworkUtil {/*** 获取ip地址*/public static String getIpAddress(HttpServletRequest request) {String ip = request.getHeader("x-forwarded-for");if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_CLIENT_IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_X_FORWARDED_FOR");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}// 本机访问if ("localhost".equalsIgnoreCase(ip) || "127.0.0.1".equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)){// 根据网卡取本机配置的IPInetAddress inet;try {inet = InetAddress.getLocalHost();ip = inet.getHostAddress();} catch (UnknownHostException e) {e.printStackTrace();}}// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割if (null != ip && ip.length() > 15) {if (ip.indexOf(",") > 15) {ip = ip.substring(0, ip.indexOf(","));}}return ip;}/*** 获取mac地址*/public static String getMacAddress() throws Exception {// 取mac地址byte[] macAddressBytes = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();// 下面代码是把mac地址拼装成StringStringBuilder sb = new StringBuilder();for (int i = 0; i < macAddressBytes.length; i++) {if (i != 0) {sb.append("-");}// mac[i] & 0xFF 是为了把byte转化为正整数String s = Integer.toHexString(macAddressBytes[i] & 0xFF);sb.append(s.length() == 1 ? 0 + s : s);}return sb.toString().trim().toUpperCase();}}

好了,ip 获取到了至于查询 ip 归属地嘛

Ip2region

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。