将MAC地址字节数组格式化为String [英] Formatting MAC address byte array to String

查看:161
本文介绍了将MAC地址字节数组格式化为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码查找计算机的MAC地址。此代码直接打印MAC地址,但我想将其作为字符串返回。我完全糊涂了。

I am using this code to find the MAC address of a machine. This code prints directly the MAC address, but I want to return it as a string. I am completely confused.

请帮忙。

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格式的函数,

There is no standard text representation for Mac addresses. You just need to convert it to hex and separate the bytes for readability. Here is the function I use in the format of ifconfig on Unix,

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();
}

您只需将':'更改为' - '。

You just need to change the ':' to '-'.

这篇关于将MAC地址字节数组格式化为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆