Friday, January 15, 2010

Test if IPv4 belongs to a private network address

Sometime we need to check if a given IP belongs to a private network. IP of a private network belong to a special range of IPs. It is most likely, that if you have a small local network at your home or work, the IP in that network is starting with “192” or “10”. For example: “192.168.0.1” or “10.0.0.1”.

The ranges of private network IPs is:



STARTEND
10.0.0.010.255.255.255
172.16.0.0 172.31.255.255
192.168.0.0 192.168.255.255

Since we are dealing here with range of IPs, it will be much easier to convert the IPs to long representation. We will use the code from this blog: Convert IP String to numeric representation and numeric representation to IP String in Java, to easily do the job.

Let’s have a look at the function “isIPv4Private”:

package com.bashan.blog.ip;
/**
 * @author Bashan
 */
public class IpUtils {
  public static String longToIpV4(long longIp) {
    int octet3 = (int) ((longIp >> 24) % 256);
    int octet2 = (int) ((longIp >> 16) % 256);
    int octet1 = (int) ((longIp >> 8) % 256);
    int octet0 = (int) ((longIp) % 256);
    return octet3 + "." + octet2 + "." + octet1 + "." + octet0;
  }
  public static long ipV4ToLong(String ip) {
    String[] octets = ip.split("\\.");
    return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) +
        (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]);
  }
  public static boolean isIPv4Private(String ip)
  {
    long longIp = ipV4ToLong(ip);
    return (longIp >= ipV4ToLong("10.0.0.0") && longIp <= ipV4ToLong("10.255.255.255")) ||
        (longIp >= ipV4ToLong("172.16.0.0") && longIp <= ipV4ToLong("172.31.255.255")) ||
        longIp >= ipV4ToLong("192.168.0.0") && longIp <= ipV4ToLong("192.168.255.255");
  }
  public static void main(String[] args) {
    System.out.println(isIPv4Private("210.5.80.10"));
    System.out.println(isIPv4Private("192.168.0.1"));
  }
}
You can download the class here.

No comments:

Post a Comment