7

如何将 MacAddress 转换为十六进制字符串,然后将其解析为 java 中的字节?以及类似的IP地址?

谢谢

4

2 回答 2

18

MAC 地址已经是十六进制格式,它是 6 对 2 个十六进制数字的形式。

String macAddress = "AA:BB:CC:DD:EE:FF";
String[] macAddressParts = macAddress.split(":");

// convert hex string to byte values
Byte[] macAddressBytes = new Byte[6];
for(int i=0; i<6; i++){
    Integer hex = Integer.parseInt(macAddressParts[i], 16);
    macAddressBytes[i] = hex.byteValue();
}

和...

String ipAddress = "192.168.1.1";
String[] ipAddressParts = ipAddress.split("\\.");

// convert int string to byte values
Byte[] ipAddressBytes = new Byte[4];
for(int i=0; i<4; i++){
    Integer integer = Integer.parseInt(ipAddressParts[i]);
    ipAddressBytes[i] = integer.byteValue();
}
于 2012-05-31T18:41:25.980 回答
1

开源 IPAddress Java 库将解析 MAC 地址和 IP 地址,并以多态方式转换为字节。免责声明:我是那个图书馆的项目经理。

以下代码将满足您的要求:

    String ipv4Addr = "1.2.3.4";
    String ipv6Addr = "aaaa:bbbb:cccc:dddd::";
    String macAddr = "a:b:c:d:e:f";
    try {
        HostIdentifierString addressStrings[] = {
            new IPAddressString(ipv4Addr),
            new IPAddressString(ipv6Addr),
            new MACAddressString(macAddr)
        };
        Address addresses[] = new Address[addressStrings.length];
        for(int i = 0; i < addressStrings.length; i++) {
            addresses[i] = addressStrings[i].toAddress();//parse
        }
        for(Address addr : addresses) {
            byte bytes[] = addr.getBytes();
            //convert to a list of positive Integer for printing
            List<Integer> forPrinting = IntStream.range(0, bytes.length).map(idx -> 0xff & bytes[idx]).boxed().collect(Collectors.toList());
            System.out.println("bytes for " + addr + " are " + forPrinting);
        }
    } catch(HostIdentifierException | IOException e) {
        //e.getMessage has validation error
    }

输出:

    bytes for 1.2.3.4 are [1, 2, 3, 4]
    bytes for aaaa:bbbb:cccc:dddd:: are [170, 170, 187, 187, 204, 204, 221, 221, 0, 0, 0, 0, 0, 0, 0, 0]
    bytes for 0a:0b:0c:0d:0e:0f are [10, 11, 12, 13, 14, 15]
于 2018-01-10T19:58:58.057 回答