1

i have a db with range of IP and country. i get the user IP and want to know the country

the data is

from     |to     |country
-------------------------
1.1.1.1.1|2.2.2.2| US
5.5.5.5.5|6.6.6.6| CN

how can i find what country is ip 5.6.0.0?

eyalb
  • 2,994
  • 9
  • 43
  • 64
  • 2
    What kind of IP addresses have five values separated by dots? IPV5? Try converting IPV4 addresses to `uint` values and comparing those. 1.2.3.4 => `( ( ( 1 * 256 + 2 ) * 256 + 3 ) * 256 + 4`. – HABO Jul 31 '14 at 13:11
  • 3
    There's some answers on this already - [1](http://stackoverflow.com/questions/1270091/how-to-determine-if-an-ip-address-belongs-to-a-country), [2](http://stackoverflow.com/questions/18266958/how-to-find-country-from-ip-adress) – Jonesopolis Jul 31 '14 at 13:11

2 Answers2

0

You simple check after splitting the addresses with '.'. Starting comparing left to right for each splitted value.

For example:

bool BelongsOrNot(String from, String to, String ip) {
   String []froms = from.Split(".");
   String []tos = to.Split(".");
   String []ips = ip.Split(".");
   for(var i=0;i<ips.length; i++){
      int ipi = Int32.Parse(ips[i]);
      int fromi = Int32.Parse(frons[i]);
      int toi = Inte32.Parse(tos[i]);
      if(toi>ipi && fromi < ipi){
        return false;
      }
   }
   return true;
}

Hope this helps.

Pankaj Sharma
  • 669
  • 5
  • 12
0

Create a new class IP as follows:

public class IP : System.Net.IPAddress, IComparable<IP>
{
    public IP(long newAddress) : base(newAddress)
    {
    }

    public IP(byte[] address, long scopeid) : base(address, scopeid)
    {
    }

    public IP(byte[] address) : base(address)
    {
    }


    public int CompareTo(IP other)
    {
        byte[] ip1 = GetAddressBytes();
        byte[] ip2 = other.GetAddressBytes();
        for (int i = 0; i < ip1.Length; i++)
        {
            if (ip1[i] > ip2[i])
                return 1;
            if (ip1[i] < ip2[i])
                return -1;
        }
        return 0;
    }
}

To check if the specified IP belongs to the range:

IP ipRangeLow = new IP(new byte[] { 5, 5, 5, 5 });
IP ipRangeHigh = new IP(new byte[] { 6, 6, 6, 6 });

IP ip = new IP(new byte[] { 5, 6, 0, 0 });
bool ipInRange = ip.CompareTo(ipRangeLow) >= 0 && ip.CompareTo(ipRangeHigh) <= 0;
Dmitry
  • 13,797
  • 6
  • 32
  • 48