2010-05-09 2 views
7

J'utilise ce code pour trouver l'adresse MAC d'une machine. Ce code imprime directement l'adresse MAC, mais je veux le renvoyer en tant que chaîne. Je suis complètement confus.Formatage d'un tableau d'octets d'adresse MAC en String

aidez s'il vous plaît.

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

Si vous avez besoin de renvoyer une chaîne formatée de la même manière, utilisez un StringBuilder et ajoutez-y des parties de boucle formatées avec String.format (..). –

+0

Voir http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c/632920#632920 – Zaki

Répondre

18

Il n'y a pas de représentation textuelle standard pour les adresses Mac. Vous avez juste besoin de le convertir en hex et séparer les octets pour plus de lisibilité. Voici la fonction que j'utilise dans le format de ifconfig sur 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(); 
} 

Vous avez juste besoin de changer le « : » à « - ».

+0

Cela semble agréable de moi. Il est également possible d'éviter String.format() si la performance est un problème car c'est une fonction notoirement lente. – Chris

+0

Il me donne NullPointerException à la ligne 'NetworkInterface ni = NetworkInterface.getByInetAddress (addr);' mais mon objet InetAddress contient IPAddress valide ... toute aide est appréciée .... – Durrat

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

Il devrait être quelque chose comme

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(); 
-1
String s=""; 
for (int i = 0; i < mac.length; i++) { 
    s += String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""); 
} 
+1

La concaténation des chaînes avec + = est extrêmement inefficace (utilisez un StringBuilder plutôt comme dans les autres réponses). En outre, il semble que vous ayez regroupé trop de code sur une seule ligne, ce qui n'aide ni n'empêche les performances, mais produit du code illisible lorsqu'il est mis à l'échelle jusqu'à plusieurs milliers de lignes. – Chris

4

Par cela, vous pouvez facilement formate Adresse Mac 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(); 

    } 

    } 

} 

copie d'ici: http://www.mkyong.com/java/how-to-get-mac-address-in-java/comment-page-1/#comment-139182

0

Je sais que c'est une question liée à Java, mais pour les utilisateurs Scala qui ont fini ici comme je l'ai fait, c'est une façon de le faire à Scala:

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