java get ipv4 address on local network

Viewed 375

I want to get ipv4 adress and i am writing this code:

System.out.println(InetAddress.getLocalHost());

it is returning different ip address. I explained my problem in image:

I want to take green ip address but it's giving to me red ip address.

enter image description here

1 Answers

InetAddress.getLocalHost() is apparently returning the address for "Ethernet adapter VirtualBox Host-Only Network". You seem to want the address for "Wireless LAN adapter Wi-Fi".

Iterate through the available network devices on your computer using NetworkInterface.getNetworkInterfaces(), checking the device name via NetworkInterface#getDisplayName().

Once you found the interface you want, use NetworkInterface#getInetAddresses() to obtain the addresses provided by that interface. Iterating over this will give you access to the address you desire.

See Listing Network Interface Addresses

Related