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?
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?
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.
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;