Created
September 21, 2013 16:21
-
-
Save madan712/6651967 to your computer and use it in GitHub Desktop.
Java program to check IP address range. This is a simple java program to check IP address range. Here we provide a IP address to check whether it lies between start and end IP address.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.InetAddress; | |
import java.net.UnknownHostException; | |
public class IPRangeChecker { | |
public static long ipToLong(InetAddress ip) { | |
byte[] octets = ip.getAddress(); | |
long result = 0; | |
for (byte octet : octets) { | |
result <<= 8; | |
result |= octet & 0xff; | |
} | |
return result; | |
} | |
public static boolean isValidRange(String ipStart, String ipEnd, | |
String ipToCheck) { | |
try { | |
long ipLo = ipToLong(InetAddress.getByName(ipStart)); | |
long ipHi = ipToLong(InetAddress.getByName(ipEnd)); | |
long ipToTest = ipToLong(InetAddress.getByName(ipToCheck)); | |
return (ipToTest >= ipLo && ipToTest <= ipHi); | |
} catch (UnknownHostException e) { | |
e.printStackTrace(); | |
return false; | |
} | |
} | |
public static void main(String[] args) { | |
System.out.println(isValidRange("122.170.122.0", "122.170.122.255", | |
"122.170.122.215")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
looks clean, thanks for the idea.