Convert IP address to number PDF Print E-mail
Written by Charles   
Monday, 13 October 2008 11:09

IP addresses are actually numbers. Of course they are represented in octet-string form
but you might need one as a number: here's how (source code HERE):



/**
* Various IP address utils
*
* @author Charles Johnson
*/
public class IpConvert {
/**
* For testing purposes
*
* @param args Test arguments
*/
public static void main(String[] args) {
System.out.println(toHex(args[0]));
System.out.println(ipToLong(args[0]));
}

/**
* Convert an IP address to a hex string
*
* @param ipAddress Input IP address
*
* @return The IP address in hex form
*/
public static String toHex(String ipAddress) {
return Long.toHexString(IpConvert.ipToLong(ipAddress));
}

/**
* Convert an IP address to a number
*
* @param ipAddress Input IP address
*
* @return The IP address as a number
*/
public static long ipToLong(String ipAddress) {
long result = 0;
String[] atoms = ipAddress.split("\\.");

for (int i = 3; i >= 0; i--) {
result |= (Long.parseLong(atoms[3 - i]) << (i * 8));
}

return result & 0xFFFFFFFF;
}
}


Comments
Add New Search
George  - Colours   |89.213.64.xxx |2008-10-22 15:23:27
I like the code, but the colours work against legibility a little I find.
Write comment
Name:
Email:
 
Website:
Title:
UBBCode:
[b] [i] [u] [url] [quote] [code] [img] 
 
 
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
 
Please input the anti-spam code that you can read in the image.

3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

Last Updated ( Monday, 13 October 2008 11:34 )