简体   繁体   中英

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

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

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...

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.

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