简体   繁体   中英

How To Check IP with Given IP Range on LINQ C#

I've an SQL Query like

WHERE Network <= @ipaddress AND LastIp >= @ipaddress  

and i need to convert it to LINQ Query. Network and LastIp columns are string. I'm receiving @ipaddress from input at application.

string.Compare(ip.Network,ipAddress) == -1
&& string.Compare(ip.LastIp,ipAddress) == 1 

is it okey to use string.Compare or is there another and much safer way to do that? So thankful for any help.

PS: Need to compare directly into LINQ Query with Repository Context. So i tried to use IpAddress function but it gave the LINQ Expression error.

You can convert IP to uint using the following function:

  public uint IpAddressToUint(string ipAddress)
  {
      var address = IPAddress.Parse(ipAddress);
      byte[] bytes = address.GetAddressBytes();
      return BitConverter.ToUInt32(bytes, 0);
  }

and compare uints:

IpAddressToUint(ip.Network) <= IpAddressToUint(ipAddress) && 
IpAddressToUint(ip.LastIp) >= IpAddressToUint(ipAddress)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM