EyeSeeSharp
EyeSeeSharp

Reputation: 645

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#?

Upvotes: 0

Views: 830

Answers (4)

xanatos
xanatos

Reputation: 111850

You can directly check the bytes of the IP:

byte[] bytes = ip.GetAddressBytes();

// Check ipv4
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
    if (bytes[0] == 10 && bytes[1] == 80) {

    }
}

Upvotes: 1

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12205

byte[] bytes = ipAddress.GetAddressBytes();
bool ok = bytes.Length >= 2 && bytes[0] == 10 && bytes[1] == 80;

Upvotes: 2

user3021830
user3021830

Reputation: 2924

@Flater is quite true. You can additionally use this

bool IsCorrectIP = false;
string[] iparr = ipstring.Split(new char[] { '.' ,StringSplitOptions.RemoveEmptyEntries });
if(iparr[0] = "10" && iparr[1] == 80)
{    
    IsCorrectIP = true;
}

But even I'd go for the @Flater's solution :)

Upvotes: 0

Flater
Flater

Reputation: 13773

Have you tried:

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

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

Upvotes: 6

Related Questions