java web根据访问的ip地址获取MAC地址

本文介绍了一种通过Java代码获取客户端MAC地址的方法,并针对Windows和Linux操作系统进行了适配。文中提供了一个实用的代码示例,该示例首先获取客户端IP地址,然后根据不同操作系统调用不同命令来获取MAC地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<span style="white-space:pre">	</span>/**
	 * 取客户端MAC地址
	 * @author huangwg 2014-06-26
	 */
	public static String getMACAddress(HttpServletRequest request) {
		String macAddress = "";
		String ip = getClientIPAddress(request);
		
		Properties props = System.getProperties();
		if(props.get("os.name").toString().contains("Window")){	//判断操作系统
			if(ip.equals("127.0.0.1")){			//本机的IP地址查询不了,要转成192.xxx.xxx.xxx的形式
				InetAddress addr = null;
				try {
					addr = InetAddress.getLocalHost();
					ip=addr.getHostAddress().toString();
				} catch (UnknownHostException e) {
					ip = "127.0.0.1";
				}
			}
			String str = "";
			try {
				Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
				InputStreamReader ir = new InputStreamReader(p.getInputStream());
				LineNumberReader input = new LineNumberReader(ir);
				for (int i = 1; i < 100; i++) {
					str = input.readLine();
					if (str != null) {
						if (str.contains("MAC Address")) {
							macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
							break;
						}else if(str.contains("MAC 地址")){		//有的机器会显示中文
							macAddress = str.substring(str.indexOf("MAC 地址") + 9, str.length());
							break;
						}
					}
				}
			} catch (IOException e) {
				return "";
			}
		} else {
			try {
				Runtime.getRuntime().exec("ping -c1 " + ip);
				Process p = Runtime.getRuntime().exec(
						new String[] { "/bin/sh", "-c", "arp | grep " + ip + " | awk '{print $3}'" });
				InputStreamReader ir = new InputStreamReader(p.getInputStream());
				LineNumberReader input = new LineNumberReader(ir);
				macAddress = input.readLine();
			} catch (IOException e) {
				return "";
			}
		}
		return macAddress;
	}

在网上找到了两种方案,一种是通过js来获取,但是由于IE安全性的问题会有弹出提示框,让客户设备很麻烦所以放弃了。

一种是能过java代码,在网上只找到在window下的,没有Linux的,所以改良了一下。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值