Article

SQL format. Convert IP address to IP number

The table worldip contains fields start, end and code. Every row means a network. start and end are integer fields with IP numbers, code is a double-character country code, like "US".
You can convert every IP address to IP number with following formula:
IP Number = 16777216*A + 65536*B + 256*C + D
where IP Address = A.B.C.D
There is function ip2long($ip_address) in PHP that returns IP number.
For example, IP Address 91.121.147.207 converts to the IP number 1534694351

Than you can get the country code with following request:
SELECT code FROM worldip WHERE (start<=IP_NUMBER and end>=IP_NUMBER)
If you install second table with country names, you get both country code and name with this request:
SELECT wl.code,wl.country FROM worldip w LEFT JOIN worldip_land wl
 ON (w.code=wl.code) WHERE (w.start<=IP_NUMBER and w.end>=IP_NUMBER)
or just country name:
SELECT wl.country FROM worldip_land wl LEFT JOIN worldip w
 ON (w.code=wl.code) WHERE (w.start<=IP_NUMBER and w.end>=IP_NUMBER)

If you use API (to get the most current date), you can install only one tabel with country names.
SELECT country FROM worldip_land WHERE code="GB"
gives back "United Kingdom"

You can replace IP_NUMBER with inet_aton('IP_ADDR')
SELECT code FROM worldip WHERE 
(start<=inet_aton('77.77.77.77') and end>=inet_aton('77.77.77.77'))
mgyk Sweden02 Sep 2008 06:09#12Русский   
Дима Ukraine02 Sep 2008 12:09#13Русский   
wipmania logo Alrond 02 Sep 2008 13:09#14Русский   
Ncs Russia03 Sep 2008 05:09#15Русский   
deeonis Latvia04 Mar 2009 10:03#672Русский   
wipmania logo Alrond 08 Mar 2009 17:03#690Русский   

Anonymous/Name OpenID OpenID Yahoo! OpenID AOL WordPress LiveJournal TypePad Vox Myvidoop Orange Yandex YandexBlog Mixi Myspace Flickr Verisign MyOpenID ClaimID

All fields are not required

Leave blank for main post.
Comment - 5000 characters maximum. BBcode is allowed.

Subscribe to answers: to all comments:RSS comments (en)

Please have a look at our
Facebook Page and leave a comment

Creative Commons License
Creative Commons Attribution-Noncommercial 3.0 License