0

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.
fifauser
  • 51
  • 4
  • "is it okey to use string.Compare" have you encountered an issue using it? – gunr2171 Jan 04 '23 at 13:52
  • Hello fifauser, there is no 'greater than' or 'less then' comparison operator available with IPAddress, you should build a function by yourself. I think you could find some classes ready to use with an online search. – Manuel Fabbri Jan 04 '23 at 13:52
  • 1
    An IPv4 number can be converted into an unsigned 32-bit integer. These numbers can be compared and check if they fall into a specific range. – Oliver Jan 04 '23 at 13:54
  • @ManuelFabbri thank you i will check out. – fifauser Jan 04 '23 at 13:54
  • @gunr2171 actually no but i just wondered if there is any other option – fifauser Jan 04 '23 at 13:55
  • https://stackoverflow.com/questions/461742/how-to-convert-an-ipv4-address-into-a-integer-in-c/13350494#13350494 – Oliver Jan 04 '23 at 13:56
  • There are some methods in this [issue](https://stackoverflow.com/questions/160776/how-would-you-compare-ip-address), Maybe you can refer to it. – Xinran Shen Jan 05 '23 at 07:15

1 Answers1

1

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)
Hossein Sabziani
  • 1
  • 2
  • 15
  • 20