Java IP Addresses
Recently I need to convert a dotted decimal IP address into a decimal IP address (a long integer). For some reason Java doesn’t have this built in and everywhere I found on the net appeared to have made a real meal of implementing it. So hopefully you’ll find this bit of code useful:
public static long Dda2L(String IPAddress) {
String[] result;
/*
* We need to convert aaa.bbb.ccc.ddd to a number
*/
result = IPAddress.split(”\\.”);
if (result.length != 4) {
return -1L;
}
if ((Integer.parseInt(result[0]) < 0 || Integer.parseInt(result[0]) > 255)
||(Integer.parseInt(result[1]) < 0 || Integer.parseInt(result[1]) > 255)
||(Integer.parseInt(result[2]) < 0 || Integer.parseInt(result[2]) > 255)
||(Integer.parseInt(result[3]) < 0 || Integer.parseInt(result[3]) > 255)) {
return -1L;
}
else {
return ((Long.parseLong(result[0])) < < 24
| (Long.parseLong(result[1])) << 16
| (Long.parseLong(result[2])) << 8
| (Long.parseLong(result[3])));
}
}
July 10th, 2006 at 11:50 pm
Hi,
I was looking for some code to convert IPv4 to Integer, and your code is very, very usefull, small and efficient!
July 11th, 2006 at 9:04 am
No problem at all. I’m glad you found it useful. To be honest I’m still amazed that this sort of function isn’t built into a language such as Java! Maybe it is and someone will put us straight