0

How to get all IP adresses of a Linux machine using Java?

My device has two IP adresses, but while trying to get all IP addresses by using the below, it will return only a primary IP address. The same piece of code works fine for Windows.

InetAddress myAddr = InetAddress.getLocalHost();
System.out.println("myaddr::::" + myAddr.getHostName());
InetAddress localAddress[] = InetAddress.getAllByName(myAddr.getHostName());
int len = localAddress.length;
for(int i = 0; i < len; i++)
{
  String localaddress = localAddress[i].getHostAddress().trim();
  System.out.println("localaddress::::" + localaddress);
}
Eregrith
  • 4,263
  • 18
  • 39
mreaevnia
  • 578
  • 2
  • 6
  • 15
  • 4
    Look at [How to get the ip of the computer on linux through Java](http://stackoverflow.com/questions/901755/how-to-get-the-ip-of-the-computer-on-linux-through-java) – cubanacan Sep 11 '12 at 07:47

3 Answers3

1

I believe you should take a look on NetworkInterfaces class of Java. You'll query for all available interfaces and enumerate over them to get the details (ip address in your case ) assigned to each one of there.

You can find example and explanations Here

Hope this helps

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

try this, you can get

 InetAddress address = InetAddress.getLocalHost();
 NetworkInterface neti = NetworkInterface.getByInetAddress(address);
 byte macadd[] = neti.getHardwareAddress();
 System.out.println(macadd);
user3032819
  • 595
  • 1
  • 5
  • 6
0

Try this,

import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

public static void main(String args[]) throws SocketException, UnknownHostException {
     System.out.println(System.getProperty("os.name"));
     Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface netint : Collections.list(nets))
        displayInterfaceInformation(netint);     
}

static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
    out.printf("Display name: %s\n", netint.getDisplayName());
    out.printf("Name: %s\n", netint.getName());
    Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
    for (InetAddress inetAddress : Collections.list(inetAddresses)) {

        out.printf("InetAddress: %s\n", inetAddress);
    }
    out.printf("\n");
 }
}  
Thirumal
  • 8,280
  • 11
  • 53
  • 103