内容简介:翻译自:https://stackoverflow.com/questions/2797430/formatting-mac-address-byte-array-to-string
我正在使用此代码查找计算机的MAC地址.此代码直接打印MAC地址,但我想将其作为字符串返回.我完全糊涂了.
请帮忙.
try { InetAddress add = InetAddress.getByName("10.123.96.102"); NetworkInterface ni1 = NetworkInterface.getByInetAddress(add); if (ni1 != null) { byte[] mac1 = ni1.getHardwareAddress(); if (mac1 != null) { for (int k = 0; k < mac1.length; k++) { System.out.format("%02X%s", mac1[k], (k < mac1.length - 1) ? "-" : ""); } } else { System.out.println("Address doesn't exist "); } System.out.println(); } else { System.out.println("address is not found."); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); }
Mac地址没有标准的文本表示.您只需将其转换为十六进制并将字节分开以便于阅读.这是我在Unix上使用ifconfig格式的函数,
public static String getMacAddress(String ipAddr) throws UnknownHostException, SocketException { InetAddress addr = InetAddress.getByName(ipAddr); NetworkInterface ni = NetworkInterface.getByInetAddress(addr); if (ni == null) return null; byte[] mac = ni.getHardwareAddress(); if (mac == null) return null; StringBuilder sb = new StringBuilder(18); for (byte b : mac) { if (sb.length() > 0) sb.append(':'); sb.append(String.format("%02x", b)); } return sb.toString(); }
您只需将’:’更改为’ – ‘即可.
翻译自:https://stackoverflow.com/questions/2797430/formatting-mac-address-byte-array-to-string
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。