Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test with Java if two IPs are in the same network

Tags:

java

ip

subnet

How can I test if two IPs are in the same network according to the subnet mask?

For example I have the IPs 1.2.3.4 and 1.2.4.3: Both are in the same network if the mask is 255.0.0.0 or 255.255.0.0 or even 255.255.248.0 but not if the mask is 255.255.255.0..

like image 938
xZise Avatar asked Dec 19 '11 00:12

xZise


2 Answers

Try this method:

public static boolean sameNetwork(String ip1, String ip2, String mask) 
throws Exception {

    byte[] a1 = InetAddress.getByName(ip1).getAddress();
    byte[] a2 = InetAddress.getByName(ip2).getAddress();
    byte[] m = InetAddress.getByName(mask).getAddress();

    for (int i = 0; i < a1.length; i++)
        if ((a1[i] & m[i]) != (a2[i] & m[i]))
            return false;

    return true;

}

And use it like this:

sameNetwork("1.2.3.4", "1.2.4.3", "255.255.255.0")
> false

EDIT :

If you already have the IPs as InetAddress objects:

public static boolean sameNetwork(InetAddress ip1, InetAddress ip2, String mask) 
throws Exception {

    byte[] a1 = ip1.getAddress();
    byte[] a2 = ip2.getAddress();
    byte[] m = InetAddress.getByName(mask).getAddress();

    for (int i = 0; i < a1.length; i++)
        if ((a1[i] & m[i]) != (a2[i] & m[i]))
            return false;

    return true;

}
like image 173
Óscar López Avatar answered Oct 03 '22 18:10

Óscar López


Simple enough: mask & ip1 == mask & ip2 - you have to interpret the IPs all as a single number for that but that should be obvious.

like image 34
Voo Avatar answered Oct 03 '22 17:10

Voo