For a machine with multiple NIC cards, is there a convenient method in Java that tells whether a given IP address is the current machine or not. e.g.
boolean IsThisMyIpAddress("192.168.220.25");
Usually, you can access the localhost of any computer through the loopback address 127.0. 0.1. By default, this IP address references a server running on the current device. In other words, when your computer requests the IP address 127.0.
All you have to go on is the ip address sent in the request. To see if an IP is on the same network, you take your subnet mask and perform a bitwise AND with your own IP. If you perform the same result with the other IP (with your subnet mask), the results should equal if they're on the same network (subnet).
On almost all networking systems, localhost uses the IP address 127.0. 0.1. That is the most commonly used IPv4 “loopback address” and it is reserved for that purpose.
Hosts that have more than one network interface usually have one Internet address for each interface. Such hosts are called multi-homed hosts. For example, dual-stack hosts are multi-homed because they have both an IPv4 and an IPv6 network address.
If you are looking for any IP address that is valid for the local host then you must check for special local host (e.g. 127.0.0.1) addresses as well as the ones assigned to any interfaces. For instance...
public static boolean isThisMyIpAddress(InetAddress addr) { // Check if the address is a valid special local or loop back if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) return true; // Check if the address is defined on any interface try { return NetworkInterface.getByInetAddress(addr) != null; } catch (SocketException e) { return false; } }
With a string, indicating the port, call this with:
boolean isMyDesiredIp = false; try { isMyDesiredIp = isThisMyIpAddress(InetAddress.getByName("192.168.220.25")); //"localhost" for localhost } catch(UnknownHostException unknownHost) { unknownHost.printStackTrace(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With