how to compare ip addresses

前端 未结 6 512
梦如初夏
梦如初夏 2020-12-18 15:34

How to compare IP Address that is stored in an array of Ip[0] with remote Endpoint?? Please Help me.

相关标签:
6条回答
  • 2020-12-18 16:13

    I'm assuming you have retrieved the IP address via

    System.Net.EndPoint ep = client.Client.RemoteEndPoint;
    System.Net.IPEndPoint ip = (System.Net.IPEndPoint)ep;
    

    If that's the case you can just compare via

    System.Net.IPEndPoint ip = (System.Net.IPEndPoint)ep;
    ip.ToString();
    if(Ip[0] == ip.toString());
    
    0 讨论(0)
  • 2020-12-18 16:14

    Well you could just get them: ToString() and then compare them. Or you can iterate through the 4 numbers that an IPV4 ip Has, and compare them.

    0 讨论(0)
  • 2020-12-18 16:18

    Simply compare each member of the struct.

    0 讨论(0)
  • 2020-12-18 16:23

    Something like this should work ...

    var ips = new[] { IPAddress.Parse( "127.0.0.1"),
                       IPAddress.Parse( "192.168.1.1"),
                       IPAddress.Parse( "10.0.0.1" ) };
    
    var ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0);
    
    if (ips[0].Equals(ep.Address))
    {
        Console.WriteLine("Equal!");
    }
    
    0 讨论(0)
  • 2020-12-18 16:23

    All the above variants will work but there's another option not mentioned here: Use the IpAddress GetAddressBytes method to obtain the address as bytes and compare them. This could be usefull if you need to make other processing (such as figuring if an Ip is in an IP class or something like this)..

    0 讨论(0)
  • 2020-12-18 16:30

    You can use this class to extend IpAddress :

    http://www.codeproject.com/Articles/26550/Extending-the-IPAddress-object-to-allow-relative-c

    0 讨论(0)
提交回复
热议问题