Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether the ipAddress is in private range

Tags:

java

How would I check to see whether the ip address is in private category ?

    if(isPrivateIPAddress(ipAddress)) {
        //do something
    }

Any suggestions will be appreciated.

UPDATED ANSWER

    private static boolean isPrivateIPAddress(String ipAddress) {

            InetAddress ia = null;

            try {
                InetAddress ad = InetAddress.getByName(ipAddress);
                byte[] ip = ad.getAddress();
                ia = InetAddress.getByAddress(ip);
            } catch (UnknownHostException e) {
                e.printStackTrace();
                return false;
            }

            return ia.isSiteLocalAddress();
        }

I wrote this method and it's working fine for me. But is there any case in which this method will not work ? I just wanted to make sure it will be working for every case.

like image 514
AKIWEB Avatar asked Mar 15 '12 22:03

AKIWEB


2 Answers

The correct method is InetAddress.isSiteLocalAddress().

Utility routine to check if the InetAddress is a site local address.

Returns: a boolean indicating if the InetAddress is a site local address; or false if address is not a site local unicast address.

like image 141
Nick Avatar answered Oct 28 '22 15:10

Nick


This is a quick hack I generated to test my own address.

import java.net.InetAddress;
import java.net.UnknownHostException;

public class LocalAddress {

    public static void main(String[] args) {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
             e.printStackTrace();
        }
        if (address.isSiteLocalAddress()) {
            System.out.println("Site Local Address: " + address.getHostAddress());
        } else {
            System.out.println("Routeable Address: " + address.getHostAddress());
        }
    }

}

EDIT: This code has not been tested for the link local addresses, localhost, or address blocks reserved for documentation. The first two cases have methods that return them. The last is not referenced in the documentation of the class.

like image 40
BillThor Avatar answered Oct 28 '22 15:10

BillThor