The first step is to convert the visitor's IP address to an IP Number. Then we can search the IP-Country-Region-City database using IP number to match a record that has the IP Number between Beginning IP Number and Ending IP Number. Then, we can search the free IP-to-Country Database to match a unique record that has the IP number fits between From IP Number and To IP Number.
An IP Address is generally of the form w.x.y.z
The IP Number = 16777216*w + 65536*x + 256*y + z
For example, if IP address is "184.108.40.206", then its IP Number "3401190660" is based on the Formula 1.
IP Address = 220.127.116.11 (w = 202, x = 186, y = 13 and z = 4)
IP Number = 16777216*202 + 65536*186 + 256*13 + 4
= 3388997632 + 12189696 + 3328 + 4
It falls in the following range of IP number in the table because it is between the "From IP number" and the "To IP number".
From the IP range, the Country Name is Malaysia and Country Code is MY.
The country-level mapping database are available for free but you will have to pay for national, regional and metropolitan databases which reveal visitor details like region, city, latitude, longitude, ZIP code, ISP and domain name from IP address.
Technique available in detail at IP-Country Database FAQ