2012-06-09 11 views
7

mi stava avendo un problema per ottenere l'indirizzo MAC di una macchina, che è stato risolto in this question utilizzando il codice seguente:Get MAC address in Java utilizzando getHardwareAddress non deterministico

Process p = Runtime.getRuntime().exec("getmac /fo csv /nh"); 
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream())); 
String line; 
line = in.readLine();   
String[] result = line.split(","); 

System.out.println(result[0].replace('"', ' ').trim()); 

Tuttavia, vorrei sapere perché questo codice non funziona Ogni volta che legge l'indirizzo MAC, restituisce un valore diverso. Per prima cosa ho pensato che fosse perché getHash, magari usando un timestamp che non so ... Ma anche rimuovendoli i cambiamenti di risultato.

Codice

public static byte[] getMacAddress() { 
     try { 
      Enumeration<NetworkInterface> nwInterface = NetworkInterface.getNetworkInterfaces(); 
      while (nwInterface.hasMoreElements()) { 
       NetworkInterface nis = nwInterface.nextElement(); 
       if (nis != null) { 
        byte[] mac = nis.getHardwareAddress(); 
        if (mac != null) { 
         /* 
         * Extract each array of mac address and generate a 
         * hashCode for it 
         */ 
         return mac;//.hashCode(); 
        } else { 
         Logger.getLogger(Utils.class.getName()).log(Level.WARNING, "Address doesn't exist or is not accessible"); 
        } 
       } else { 
        Logger.getLogger(Utils.class.getName()).log(Level.WARNING, "Network Interface for the specified address is not found."); 
       } 
       return null; 
      } 
     } catch (SocketException ex) { 
      Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     return null; 
    } 
} 

Esempio di stampa (sto stampando direttamente da array di byte, ma la sua abbastanza per vedere che diversi credo)

[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 
[[email protected] 

Grazie in anticipo

+1

si stampa il default 'toString' di un array di byte. –

risposta

9

[email protected] realtà è il metodo toString() del risultato degli array byte[].

Si consiglia di stampare il valore utilizzando new String(mac).

byte[].toString() è implementato come:

public String toString() { 
    return getClass().getName() + "@" + Integer.toHexString(hashCode()); 
} 

Dal predefinita Object.hashCode() è implementato come indirizzo nella memoria, quindi non è coerente, come si sta creando nuova Object ogni volta.

Edit:

Poiché il byte restituito è in esadecimale, così si dovrebbe convertire in stringa decimale. Il codice può vedere da here

+0

@Wee: strano, non stampa nulla con la nuova String (mac). Dubbuging adesso ... –

+0

@PedroDusso Vedi la mia risposta aggiornata. –

5

Ecco un esempio da Mkyong.com sito web su come ottenere l'indirizzo MAC in Java:

package com.mkyong; 

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

    } 

    } 

} 
4

La risposta dal pilota spagnolo non funziona se la macchina non è collegata e darà valori diversi a seconda della rete a cui sei connesso.

questo non dipende qualsiasi indirizzo ip:

public class MacAdress { 
    public static void main(String[] args) { 
     try { 
      InetAddress ip = InetAddress.getLocalHost(); 
      System.out.println("Current IP address : " + ip.getHostAddress()); 

      Enumeration<NetworkInterface> networks = 
          NetworkInterface.getNetworkInterfaces(); 
      while(networks.hasMoreElements()) { 
       NetworkInterface network = networks.nextElement(); 
       byte[] mac = network.getHardwareAddress(); 

       if (mac != null) { 
        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) ? "-" : "")); 
        } 
       } 
      } 
     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
     } catch (SocketException e){ 
      e.printStackTrace(); 
     } 
    } 
} 
2
public static String getHardwareAddress() throws Exception { 
    InetAddress ip = InetAddress.getLocalHost(); 
    NetworkInterface ni = NetworkInterface.getByInetAddress(ip); 
    if (!ni.isVirtual() && !ni.isLoopback() && !ni.isPointToPoint() && ni.isUp()) { 
     final byte[] bb = ni.getHardwareAddress(); 
     return IntStream.generate(ByteBuffer.wrap(bb)::get).limit(bb.length) 
       .mapToObj(b -> String.format("%02X", (byte)b)) 
       .collect(Collectors.joining("-")); 
    } 
    return null; 
} 
Problemi correlati