Search code examples
c#ipdigits

Check first X digits of IP address


My goal is to have code execute if the local IP of the user does not start with 10.80.

I can't find a way that isn't error prone, for example:

Here's what I have to get the I.P.:

        IPHostEntry host;
        string localIP = "?";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily.ToString() == "InterNetwork")
            {
                localIP = ip.ToString();
            }
        }
        iplabel.Text = localIP;

Then I attempted to convert this to an int to check if it's < or >:

string ipstring = iplabel.Text.Replace(".", "");
int ipnum = int.Parse(ipstring);
if (ipnum > 1080000000 && ipnum < 1080255255)
{//stuff}

But the problem is, if there is a 2 digit IP value for example 10.80.22.23 it won't work as it's checking for a number than is greater than that range.

Is there a better solution to check the first x amount of digits of an int or IP address in C#?


Solution

  • Have you tried:

    bool IsCorrectIP = ( ipstring.StartsWith("10.80.") );
    

    Sorry if the answer is too terse. But that should resolve the issue at hand.