简体   繁体   English

如何确定我的计算机的IP地址是否在指定的网络地址之下?

[英]How can I determine if my computer's IP address falls under a specified network address?

        string myHost = System.Net.Dns.GetHostName();

        string myIP = 
          System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();
        MessageBox.Show(myIP);

        TextReader read = new StreamReader(//Text file with network address);
        var ip = read.ReadLine();
        read.Close();

        if (ip == //Need help with this part)
            MessageBox.Show("You are on the network");
        else
            MessageBox.Show("You are not on the network");

I can get my computers address but I need to compare it to a network address and if it falls under that network address to show that it is. 我可以获取我的计算机地址,但是我需要将其与网络地址进行比较,如果它属于该网络地址以显示该地址。

If your program crashes when your IP is invalid, you can change it over to a try catch that checks for that exception (run it and crash it to find the exception). 如果您的IP无效时程序崩溃,则可以将其更改为尝试捕获以检查该异常的尝试(运行并崩溃以查找异常)。 This is how I validated the IP in my multiplayer with Lidgren. 这就是我与Lidgren在多人游戏中验证IP的方式。

Though this is probably not the best way, it works. 尽管这可能不是最好的方法,但它可以工作。

I recommend the IPNetwork utility that can be found on codeplex. 我建议可以在Codeplex上找到IPNetwork实用程序。 It is pretty flexible and powerful. 它非常灵活和强大。 It will allow you to do a lot of things, and determining the network for a given ip address is one of them. 它可以让您做很多事情,并且确定给定IP地址的网络就是其中之一。

http://ipnetwork.codeplex.com/ http://ipnetwork.codeplex.com/

The code should look like : 该代码应如下所示:

    var ipnetwork = IPNetwork.Parse(ip);
    if (ipnetwork.Contains(myIp)) {
        // do some work...

One simple way to see if an ip is in a range is to convert the ip and the start and end of the range to longs (a function can be written for the conversion to a long from an IP address). 查看ip是否在范围内的一种简单方法是将ip以及范围的开始和结束转换为long(可以编写一个函数,用于从IP地址转换为long)。 Then see if the ip is between the two numbers. 然后查看ip是否在两个数字之间。

For example: 例如:

IP to check: 172.17.1.25 -- Converted to long --> 172017001025 要检查的IP:172.17.1.25-转换为long-> 172017001025

Range: 范围:

Start - 172.0.0.0 -- Converted to long --> 172000000000 开始-172.0.0.0-转换为long-> 172000000000

End - 172.255.255.255 -- Converted to long --> 172255255255 结束-172.255.255.255-转换为long-> 172255255255

Now just check if the ip is between the start and end values. 现在只需检查ip是否在开始值和结束值之间即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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