JDK1.6以后新增一个类NetworkInterface
通过呢个NetworkInterface类getByInetAddress方法获取到指定ip地址和mac
public static void main(String[] args) throws UnknownHostException, SocketException { InetAddress ia = InetAddress.getLocalHost(); System.out.println("亲测有效"+what("192.168.1.47")); } public static String what(String ip) throws SocketException, UnknownHostException{ NetworkInterface ne=NetworkInterface.getByInetAddress(InetAddress.getByName("192.168.1.47")); byte[]mac=ne.getHardwareAddress(); 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().toUpperCase(); }参数传入ip,输出结果为:
每8位:44 每8位:3 每8位:2c 每8位:f0 每8位:9f 每8位:24 亲测有效44-03-2C-F0-9F-24