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