java获取局域网mac_最靠谱的JAVA局域网内通过IP地址获取MAC地址(本人亲测)

局域网内通过IP地址获取MAC地址(本人亲测)window环境下,其他环境未测试

1.[代码][Java]代码

package com.example;

import java.io.InputStream;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Cmd {

/**

* 执行单条指令

* @param cmd 命令

* @return 执行结果

* @throws Exception

*/

public static String command(String cmd) throws Exception{

Process process = Runtime.getRuntime().exec(cmd);

process.waitFor();

InputStream in = process.getInputStream();

StringBuilder result = new StringBuilder();

byte[] data = new byte[256];

while(in.read(data) != -1){

String encoding = System.getProperty("sun.jnu.encoding");

result.append(new String(data,encoding));

}

return result.toString();

}

/**

* 获取mac地址

* @param ip

* @return

* @throws Exception

*/

public static String getMacAddress(String ip) throws Exception{

String result = command("ping "+ip+" -n 2");

if(result.contains("TTL")){

result = command("arp -a "+ip);

}

String regExp = "([0-9A-Fa-f]{2})([-:][0-9A-Fa-f]{2}){5}";

Pattern pattern = Pattern.compile(regExp);

Matcher matcher = pattern.matcher(result);

StringBuilder mac = new StringBuilder();

while (matcher.find()) {

String temp = matcher.group();

mac.append(temp);

}

return mac.toString();

}

public static void main(String[] args) throws Exception {

System.out.println(System.currentTimeMillis());

System.out.println(getMacAddress("192.168.1.113"));

System.out.println(System.currentTimeMillis());

//System.out.println(command("arp -a 192.168.1.103"));

//System.out.println(System.getProperties());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值