7

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

8 回答 8

23

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

您只需要将“:”更改为“-”。

于 2010-05-09T11:34:11.137 回答
4

通过这个,您可以轻松地格式化 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

于 2013-10-28T10:39:26.707 回答
3

也许你可以使用Hex.encodeHex(bytes)commons-codec。

这里有其他方法可以做到这一点,没有 3rd 方库。

于 2010-05-09T11:10:52.557 回答
1

它应该是这样的

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();
于 2010-12-16T18:24:31.327 回答
0

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

bytes.map("%02X" format _).mkString (":")
于 2014-05-29T19:27:48.577 回答
0
String s="";
for (int i = 0; i < mac.length; i++) { 
  s += String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
于 2011-05-20T10:00:47.013 回答
0
  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();
  }
于 2010-07-01T17:52:13.050 回答
0

对于轻量级和快速的东西,请尝试以下操作。第 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);
}
于 2018-10-18T16:10:30.403 回答