Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an IP address is the local host on a multi-homed system?

Tags:

java

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"); 
like image 475
MItch Branting Avatar asked Mar 09 '10 02:03

MItch Branting


People also ask

How do I know what my local host is?

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.

How do I know if my IP is local?

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).

Is IP address same as localhost?

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.

Can a host have multiple IP addresses?

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.


1 Answers

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(); } 
like image 118
Kevin Brock Avatar answered Oct 05 '22 23:10

Kevin Brock