Reprinted: "http://stephen830.javaeye.com/blog/254742"
When analyzing the customer source of the website, it is often required to determine the country or city location of the customer based on the customer's IP address. Of course, to do this, you need to have a detailed IP address library.
In the IP address library, the country or city is usually divided by the number (long integer) converted from the IP address. The general format of the IP address library database is:
...
Startiplongnumber endiplongnumber countryname countrycode cityname
...
In the application, the customer's IP address string must be converted into a long integer before it can be searched in the address library.
The following describes how to convert an IP address from a long to a long IP address.
Java code {
Function onclick ()
{
DP. Sh. toolbar. copytoclipboard (this); Return false;
}
} "Href =" http://www.javaeye.com/topic/254742 ">
- /**
- * The IP address is converted to an integer.
- * @ Param IP
- * @ Return
- */
- Public Static LongIp2long (string IP ){
- String [] IPS = IP. Split ("[.]");
- LongNum = 16777216l * long. parselong (IPS [0]) + 65536l * long. parselong (IPS [1]) + 256 * long. parselong (IPS [2]) + long. parselong (IPS [3]);
- ReturnNum;
- }
- /**
- * Convert an integer to an IP address.
- * @ Param iplong
- * @ Return
- */
- Public StaticString long2ip (LongIplong ){
- // Long iplong = 1037591503;
- LongMask [] = {0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 };
- LongNum = 0;
- Stringbuffer ipinfo =NewStringbuffer ();
- For(IntI = 0; I <4; I ++ ){
- Num = (iplong & Mask [I])> (I * 8 );
- If(I> 0) ipinfo. insert (0 ,".");
- Ipinfo. insert (0, long. tostring (Num, 10 ));
- }
- ReturnIpinfo. tostring ();
- }
/*** Convert the IP address to an integer. * @ Param IP * @ return */public static long ip2long (string IP) {string [] IPS = IP. split ("[.] "); long num = 16777216l * long. parselong (IPS [0]) + 65536l * long. parselong (IPS [1]) + 256 * long. parselong (IPS [2]) + long. parselong (IPS [3]); Return num;}/*** convert an integer to an IP address. * @ Param iplong * @ return */public static string long2ip (long iplong) {// long iplong = 1037591503; long mask [] = {0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; long num = 0; stringbuffer ipinfo = new stringbuffer (); For (INT I = 0; I <4; I ++) {num = (iplong & Mask [I])> (I * 8); if (I> 0) ipinfo. insert (0 ,". "); ipinfo. insert (0, long. tostring (Num, 10);} return ipinfo. tostring ();}
Using the above two methods, you can easily convert an IP address string into a long number, or restore a long number into an IP address string.
Reprinted: http://www.javaeye.com/topic/254742