Java example to list Network Interface Addresses and IP:
package javamyip; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collections; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; /** * @web http://java-buddy.blogspot.com/ */ public class JavaMyIP { public static void main(String[] args) { displayMyIP(); } static void displayMyIP(){ Enumeration<NetworkInterface> nets; try { nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)){ System.out.printf(netint.getDisplayName() +"\n"); Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { System.out.printf("InetAddress: %s\n", inetAddress); } System.out.printf("\n"); } } catch (SocketException ex) { Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex); } } }
Can use functional operations in Java 8 (auto suggested by Netbeans):
package javamyip; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collections; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; /** * @web http://java-buddy.blogspot.com/ */ public class JavaMyIP { public static void main(String[] args) { displayMyIP(); } static void displayMyIP(){ Enumeration<NetworkInterface> nets; try { nets = NetworkInterface.getNetworkInterfaces(); Collections.list(nets).stream().map((netint) -> { System.out.printf(netint.getDisplayName() +"\n"); return netint; }).map((netint) -> netint.getInetAddresses()).map((inetAddresses) -> { Collections.list(inetAddresses).stream().forEach((inetAddress) -> { System.out.printf("InetAddress: %s\n", inetAddress); }); return inetAddresses; }).forEach((_item) -> { System.out.printf("\n"); }); } catch (SocketException ex) { Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex); } } }
No comments:
Post a Comment