Enumerare le interfacce di rete e loro caratteristiche

DOMANDA:

Come posso creare un elenco delle interfacce di rete con le relative caratteristiche?


RISPOSTA:

Rispondo subito con un esempio chiarificatore nella classe ElencoInterfacceDiRete:

package interfaccedirete;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class ElencoInterfacceDiRete {
   public static void main(String args[]) throws SocketException {

      Enumeration<NetworkInterface> interfaces =
             NetworkInterface.getNetworkInterfaces();

      while(interfaces.hasMoreElements()) {
         NetworkInterface netInterf = interfaces.nextElement();
         Enumeration<InetAddress> indirizzi = netInterf.getInetAddresses();

         while(indirizzi.hasMoreElements()) {
            InetAddress inetAddress = indirizzi.nextElement();
            System.out.println("Nome Interfaccia:" + netInterf.getName());
            System.out.println("Nome Visualizzato:" + netInterf.getDisplayName());

            //se c'è recupero e stampo l'indirizzo MAC
            byte[] macAddress = netInterf.getHardwareAddress();
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < macAddress.length; i++)
               sb.append(String.format("%02X%s", macAddress[i], (i < macAddress.length - 1) ? "-" : ""));
            if(sb.length()>0)
               System.out.println("Indirizzo MAC: " + sb.toString());

            System.out.println("Nome Host:" + inetAddress.getHostName());
            System.out.println("Indirizzo Host:" + inetAddress.getHostAddress());

            // check se IPv4 o IPv6
            if(inetAddress instanceof Inet4Address)
               System.out.println("IP Address: IPv4");
           else
               System.out.println("IP Address: IPv6");

            System.out.println("------------------------");
         }
      }
   }
}


Sul mio dispositivo l'output sarà:

Nome Interfaccia:lo
Nome Visualizzato:Software Loopback Interface 1
Nome Host:127.0.0.1
Indirizzo Host:127.0.0.1
IP Address: IPv4
------------------------
Nome Interfaccia:lo
Nome Visualizzato:Software Loopback Interface 1
Nome Host:PROGAN-039-WS.sviluppo.resia
Indirizzo Host:0:0:0:0:0:0:0:1
IP Address: IPv6
------------------------
Nome Interfaccia:eth3
Nome Visualizzato:Marvell Yukon 88E8056 PCI-E Gigabit Ethernet Controller
Indirizzo MAC: E0-CB-4E-00-7E-E5
Nome Host:PROGAN-039-WS.sviluppo.resia
Indirizzo Host:192.164.11.39
IP Address: IPv4
------------------------


Come potete notare, in questo modo, riusciamo ad ottenere il nome e il modello/tipologia dell'interfaccia, l'indirizzo MAC (qualora assegnato), il nome Host, l'indirizzo Host e il tipo di indirizzo (IPv4 o IPv6).


Commenti

Post popolari in questo blog

Arrotondamento e troncamento in Java

Eclipse: Shortcuts (scorciatoie) da tastiera

Strutture dati: List, Set, Map

Creare un eseguibile Java