0

I have the following code

string addrStr = "010.000.000.010";
bool parsed = IPAddress.TryParse(addrStr,out IPAddress addr);

parse returns true but the returned IPAddress is 8.0.0.8

If I change addrStr to "10.0.0.10, I get the correct result.

It's like TryParse is treating the fields of the addrString as octals.

Is this behavior correct?

1 Answers1

0

You have to remove zeros to get the result you want.

private string removeLeadingZeroesReg(string ip)
    {
        Regex removeLeadingZeroesReg = new Regex(@"^0+(?=\d)");
        string output = string.Empty;
        string[] parts = ip.Split('.');
        for (int i = 0; i < parts.Length; i++)
        {
            output += removeLeadingZeroesReg.Replace(parts[i], "");
            if (i != parts.Length - 1)
                output += ".";
        }
        return output;
    }

    private void button_Click(object sender, EventArgs e)
    {
        IPAddress addr;

        String addrStr = "010.000.000.010";

        addrStr = removeLeadingZeroesReg(addrStr);

        Console.WriteLine(addrStr);

        if (  IPAddress.TryParse(addrStr, out addr))
        {
            Console.WriteLine("Valid IP");
            Console.WriteLine(addr);
        }
        else
        {
            Console.WriteLine("Invalid IP");
        }
    }
Think2826
  • 201
  • 1
  • 7