将 MAC 地址字节数组格式化为字符串

发布于 2024-09-01 00:55:41 字数 802 浏览 12 评论 0原文

我正在使用此代码来查找机器的 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();
}

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.

please help.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

春庭雪 2024-09-08 00:55:41

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

只需将 ':' 更改为 '-' 即可。

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 '-'.

疏忽 2024-09-08 00:55:41

通过此您可以轻松格式化 Mac 地址字符串。

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class App{

   public static void main(String[] args){

    InetAddress ip;
    try {

        ip = InetAddress.getLocalHost();
        System.out.println("Current IP address : " + ip.getHostAddress());

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        byte[] mac = network.getHardwareAddress();

        System.out.print("Current MAC address : ");

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
        }
        System.out.println(sb.toString());

    } catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (SocketException e){

        e.printStackTrace();

    }

   }

}

从这里复制: http://www.mkyong.com/java/how-to-get-mac-address-in-java/comment-page-1/#comment-139182

By this you can easily formate Mac Address String.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class App{

   public static void main(String[] args){

    InetAddress ip;
    try {

        ip = InetAddress.getLocalHost();
        System.out.println("Current IP address : " + ip.getHostAddress());

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        byte[] mac = network.getHardwareAddress();

        System.out.print("Current MAC address : ");

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
        }
        System.out.println(sb.toString());

    } catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (SocketException e){

        e.printStackTrace();

    }

   }

}

copy from here : http://www.mkyong.com/java/how-to-get-mac-address-in-java/comment-page-1/#comment-139182

滥情哥ㄟ 2024-09-08 00:55:41

也许你可以使用 Hex.encodeHex (字节) 来自 commons-codec。

这里有其他方法可以做到这一点,无需第三方库。

Perhaps you could use Hex.encodeHex(bytes) from commons-codec.

Here are other ways to do this, without 3rd party libraries.

南笙 2024-09-08 00:55:41

应该是这样的

StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length(); i++) {
    b.append(String.format("%02X%s", mac[i], (i < mac.length() - 1) ? "-" : "");

String s = sb.toString();

It should be something like

StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length(); i++) {
    b.append(String.format("%02X%s", mac[i], (i < mac.length() - 1) ? "-" : "");

String s = sb.toString();
若相惜即相离 2024-09-08 00:55:41
  private static final byte[] NULL_MAC = new byte[] {0, 0, 0, 0, 0, 0};

  public static String getMacString(byte[] macAddress) {
    StringBuilder retval = new StringBuilder(17);
    if (macAddress == null) {
      macAddress = NULL_MAC;
    }
    boolean isFirst = true;
    for (byte b : macAddress) {
      if (!isFirst) {
        retval.append(":");
      } else {
        isFirst = false;
      }
      retval.append(String.format("%02x", b & 0xff));
    }
    return retval.toString();
  }
  private static final byte[] NULL_MAC = new byte[] {0, 0, 0, 0, 0, 0};

  public static String getMacString(byte[] macAddress) {
    StringBuilder retval = new StringBuilder(17);
    if (macAddress == null) {
      macAddress = NULL_MAC;
    }
    boolean isFirst = true;
    for (byte b : macAddress) {
      if (!isFirst) {
        retval.append(":");
      } else {
        isFirst = false;
      }
      retval.append(String.format("%02x", b & 0xff));
    }
    return retval.toString();
  }
花落人断肠 2024-09-08 00:55:41
String s="";
for (int i = 0; i < mac.length; i++) { 
  s += String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
String s="";
for (int i = 0; i < mac.length; i++) { 
  s += String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
把时间冻结 2024-09-08 00:55:41

我知道这是一个与 Java 相关的问题,但对于像我一样最终来到这里的 Scala 用户,这是在 Scala 中执行此操作的一种方法:

bytes.map("%02X" format _).mkString (":")

I know this is a Java related question, but for Scala users who ended up here like I did, this is a way to do it in Scala:

bytes.map("%02X" format _).mkString (":")
七颜 2024-09-08 00:55:41

对于轻量级和快速的东西,请尝试以下操作。第 3 方外部依赖很少,仅使用一些“老式”位数学。

public static String buildMACAddressString(byte[] macaddress) {
    char[] buffer = new char[macaddress.length*3];
    char[] inttohex= {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    int destIndex=0;
    byte byteValue;
    for (int i = 0; i < macaddress.length; i++) {
        // pull current byte value
        byteValue = (byte) (macaddress[i] & 0xff);
        // convert high nibble to hex char and store into char array..
        buffer[destIndex++]=inttohex[(byteValue&0xf0)>>4];
        // Convert low nibble to hex char and store into char array..
        buffer[destIndex++]=inttohex[byteValue&0xf];
        // Inject spacer
        if (i < macaddress.length-1)
            buffer[destIndex++]=':';
    }
    return String.valueOf(buffer,0,destIndex);
}

For something lightweight and fast, try the following. 3rd party external dependencies are minimal and just uses some "old school" bit math.

public static String buildMACAddressString(byte[] macaddress) {
    char[] buffer = new char[macaddress.length*3];
    char[] inttohex= {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    int destIndex=0;
    byte byteValue;
    for (int i = 0; i < macaddress.length; i++) {
        // pull current byte value
        byteValue = (byte) (macaddress[i] & 0xff);
        // convert high nibble to hex char and store into char array..
        buffer[destIndex++]=inttohex[(byteValue&0xf0)>>4];
        // Convert low nibble to hex char and store into char array..
        buffer[destIndex++]=inttohex[byteValue&0xf];
        // Inject spacer
        if (i < macaddress.length-1)
            buffer[destIndex++]=':';
    }
    return String.valueOf(buffer,0,destIndex);
}
月下伊人醉 2024-09-08 00:55:41

有一种新方法,但似乎需要 Java 17。

您可以使用java.util.HexFormat类,专门定义一种格式(例如ofDelimiter(":"),还有更多格式化的可能性),然后使用格式化程序(例如hexFormat.formatHex(ni.getHardwareAddress()))。

    private List<String> getHardwareAddresses(List<byte[]> ipAddresses) {
        HexFormat hexFormat = HexFormat.ofDelimiter(":");
        List<String> hardwareAddresses = new ArrayList<>();
        try {
            for (byte[] ipAddress : ipAddresses) {
                NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ipAddress));
                if (ni.getHardwareAddress() != null) {
                    hardwareAddresses.add(hexFormat.formatHex(ni.getHardwareAddress()));
                }
            }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        }
        return hardwareAddresses;
    }

在上面的示例中,我有一个 IP 地址列表 List ,并使用它们来获取这些设备的 MAC 地址(如果可用)(if (ni.getHardwareAddress() != null) {...})。

There is a new way, but it seems it requires Java 17.

You can use the java.util.HexFormat class, specifically define a format (e.g. ofDelimiter(":"), there are many more formatting possibilities), and then use the formatter (e.g. hexFormat.formatHex(ni.getHardwareAddress())).

    private List<String> getHardwareAddresses(List<byte[]> ipAddresses) {
        HexFormat hexFormat = HexFormat.ofDelimiter(":");
        List<String> hardwareAddresses = new ArrayList<>();
        try {
            for (byte[] ipAddress : ipAddresses) {
                NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ipAddress));
                if (ni.getHardwareAddress() != null) {
                    hardwareAddresses.add(hexFormat.formatHex(ni.getHardwareAddress()));
                }
            }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        }
        return hardwareAddresses;
    }

In the example above I have a list of IP addresses as List<byte[]> and use them to get the MAC addresses of those devices if available (if (ni.getHardwareAddress() != null) {...}).

小帐篷 2024-09-08 00:55:41

Java 17+:

private static String formatMacHex(byte[] mac) {
    return HexFormat.ofDelimiter("-").formatHex(mac);
}

Java 17+:

private static String formatMacHex(byte[] mac) {
    return HexFormat.ofDelimiter("-").formatHex(mac);
}
逐鹿 2024-09-08 00:55:41

科特林版本:

private fun convertToMacAddress(macByteArray: ByteArray): String {
    return macByteArray.joinToString(":") { String.format("%02x", it) }
}

A kotlin version:

private fun convertToMacAddress(macByteArray: ByteArray): String {
    return macByteArray.joinToString(":") { String.format("%02x", it) }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文