Thursday, April 10, 2014

How to get the internal IP address of our machine using Java (for Raspberry Pi)


Hello, today... more Java

First of all, eth0 is your ethernet card. They are labelled "ethX" starting with an X of 0, so if you had two ethernet cards, the second would be "eth1".

Now, the idea is to get the IP address of my machine (small Raspberry Pi) using Java.  Normally, we can try simply with InetAddress.getLocalHost(). But if we have more than one ethernet card or a loop perhaps this method doesn't work.

A possible solution could be:
InetAddress internalIP;

Enumeration nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) {
    if(netint.getName().equals("eth0")) {
        Enumeration inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            internalIP = inetAddress;
            break;
        }
    }
}

Now we can use internalIP.getHostAddress() to show the IP address like a string.

Hope help!!

No comments:

Post a Comment