Using Java I tried to find my PCs local IP address. However, the result hasn't been correct. To be specific, I need the Wireless LAN Adapter WiFi IPv4 address from the ipconfig
command. I looked at many different questions such as this excellent answer but it didn't become clear how to do this in Java. InetAddress.getLocalHost()
returns the wrong IP ('Ethernet-Adapter VirtualBox Host-Only Network').
I tried the following code:
public static List<String> getLocalIPAddresses() throws Exception
{
val networkInterfaces = NetworkInterface.getNetworkInterfaces();
val localIPAddresses = new ArrayList<String>();
while (networkInterfaces.hasMoreElements())
{
for (val interfaceAddress : networkInterfaces.nextElement().getInterfaceAddresses())
{
val address = interfaceAddress.getAddress();
// Find the local IP addresses
if (address.isSiteLocalAddress())
{
val localIPAddress = interfaceAddress.getAddress().toString().replace("/", "");
localIPAddresses.add(localIPAddress);
}
}
}
if (localIPAddresses.isEmpty())
{
throw new IllegalStateException("Expected the computer's local IP address but didn't get one!");
}
return localIPAddresses;
}
Note:
val
is from Lombok
.
On my machine this returns a list of 2 IP addresses:
192.168.56.1
192.168.2.103
The 'Ethernet-Adapter VirtualBox Host-Only Network' one and the correct 'Wireless LAN Adapter WiFi' one. What can I do to always guarantee the latter? Apparently checking for isSiteLocalAddress()
(a.k.a local IP addresses) is not enough. What else can be done code-wise? Filtering out 'VirtualBox' is not a foolproof-solution especially since network interface names are language-dependent:
public static List<String> getLocalIPAddresses() throws Exception
{
val networkInterfaces = NetworkInterface.getNetworkInterfaces();
val localIPAddresses = new ArrayList<String>();
while (networkInterfaces.hasMoreElements())
{
val networkInterface = networkInterfaces.nextElement();
val displayName = networkInterface.getDisplayName();
if (!displayName.contains("VirtualBox"))
{
for (val interfaceAddress : networkInterface.getInterfaceAddresses())
{
val address = interfaceAddress.getAddress();
// Find the local IP addresses
if (address.isSiteLocalAddress())
{
val localIPAddress = interfaceAddress.getAddress().toString().replace("/", "");
localIPAddresses.add(localIPAddress);
}
}
}
}
if (localIPAddresses.isEmpty())
{
throw new IllegalStateException("Expected the computer's local IP address but didn't get one!");
}
return localIPAddresses;
}
I need a platform independent solution. I'm on Windows though.