开发者

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

开发者 https://www.devze.com 2023-02-15 23:02 出处:网络
string myHost = System.Net.Dns.GetHostName(); string myIP = System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();
        string myHost = System.Net.Dns.GetHostName();

        string myIP = 
          System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();
        MessageBox.Show(myIP);开发者_JAVA技巧

        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). This is how I validated the IP in my multiplayer with Lidgren.

Though this is probably not the best way, it works.


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). Then see if the ip is between the two numbers.

For example:

IP to check: 172.17.1.25 -- Converted to long --> 172017001025

Range:

Start - 172.0.0.0 -- Converted to long --> 172000000000

End - 172.255.255.255 -- Converted to long --> 172255255255

Now just check if the ip is between the start and end values.


I recommend the IPNetwork utility that can be found on codeplex. 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.

http://ipnetwork.codeplex.com/

The code should look like :

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

精彩评论

暂无评论...
验证码 换一张
取 消