Sunday, April 17, 2016

Get my MAC address using NetworkInterface

Java example to get MAC address using NetworkInterface:



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);
                }
                
                byte[] mac = netint.getHardwareAddress();
                if(mac != null){
                    StringBuilder macAddr = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        macAddr.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : "")); 
                    }
                    System.out.printf("Hardware address (MAC): [%s]\n", macAddr.toString());
                }
                
                System.out.printf("\n");
            }
        } catch (SocketException ex) {
            Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Friday, April 15, 2016

List my IP (inetAddress)


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


Wednesday, April 13, 2016

Create ServerSocket with automatically allocated port

Create ServerSocket by calling constructor ServerSocket(int port) with port = 0,  the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

Example:
package javaechoserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaEchoServer {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            //Get a available port by passing 0 
            serverSocket = new ServerSocket(0);
            int port = serverSocket.getLocalPort();
            System.out.println("Port : " + port);
            
        } catch (IOException ex) {
            Logger.getLogger(JavaEchoServer.class.getName())
                    .log(Level.SEVERE, null, ex);
        } finally {
            if (serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(JavaEchoServer.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
}