public IPEntity Query(string ip) { IPAddress address = IPAddress.Parse(ip); if (address.AddressFamily != AddressFamily.InterNetwork) { throw new ArgumentException("不支持非IPV4的地址"); } if (IPAddress.IsLoopback(address)) { return new IPEntity() { IP = ip, Country = "本机内部环回地址", Local = string.Empty }; } long intIP = IpToInt(ip); IPEntity ipLocation = new IPEntity() { IP = ip }; uint right = (uint)ipCount; uint left = 0; uint middle = 0; uint startIp = 0; uint endIpOff = 0; uint endIp = 0; int countryFlag = 0; while (left < (right - 1)) { middle = (right + left) / 2; startIp = GetStartIp(middle, out endIpOff); if (intIP == startIp) { left = middle; break; } if (intIP > startIp) { left = middle; } else { right = middle; } } startIp = GetStartIp(left, out endIpOff); endIp = GetEndIp(endIpOff, out countryFlag); if ((startIp <= intIP) && (endIp >= intIP)) { string local; ipLocation.Country = GetCountry(endIpOff, countryFlag, out local); ipLocation.Local = local; } else { ipLocation.Country = "未知"; ipLocation.Local = string.Empty; } return ipLocation; }
public IPEntity Query(string ip) { IPAddress address = IPAddress.Parse(ip); if (address.AddressFamily != AddressFamily.InterNetwork) { throw new ArgumentException("不支持非IPV4的地址"); } if (IPAddress.IsLoopback(address)) { return(new IPEntity() { IP = ip, Country = "本机内部环回地址", Local = string.Empty }); } long intIP = IpToInt(ip); IPEntity ipLocation = new IPEntity() { IP = ip }; uint right = (uint)ipCount; uint left = 0; uint middle = 0; uint startIp = 0; uint endIpOff = 0; uint endIp = 0; int countryFlag = 0; while (left < (right - 1)) { middle = (right + left) / 2; startIp = GetStartIp(middle, out endIpOff); if (intIP == startIp) { left = middle; break; } if (intIP > startIp) { left = middle; } else { right = middle; } } startIp = GetStartIp(left, out endIpOff); endIp = GetEndIp(endIpOff, out countryFlag); if ((startIp <= intIP) && (endIp >= intIP)) { string local; ipLocation.Country = GetCountry(endIpOff, countryFlag, out local); ipLocation.Local = local; } else { ipLocation.Country = "未知"; ipLocation.Local = string.Empty; } return(ipLocation); }