Rasool Aghajani
Rasool Aghajani

Reputation: 441

Search Results Web results Parsing string to IP Address doesn't work some time

im trying for convert String IP to ipAddress but for some string this method not working as well , what is the problem? ex:

                Console.WriteLine("ip address");
                string ip = Console.ReadLine();
                System.Net.IPAddress IP = System.Net.IPAddress.Parse(ip);
                Console.WriteLine(IP);

for example if i use this string "192.168.001.011" then the IPAddress.Parse method will return me 192.168.1.9 or "192.168.1.012" will return '192.168.1.10' why ?? i'm confused really...

Upvotes: 1

Views: 148

Answers (2)

Rasool Aghajani
Rasool Aghajani

Reputation: 441

I solved my problem with this code:

Console.WriteLine("ip address");
string ip = Console.ReadLine();
string[] s = ip.Split('.');
IPAddress IP= IPAddress.Parse(Int16.Parse(s[0]) + "." + Int16.Parse(s[1]) + "." + 
Int16.Parse(s[2]) + "." + Int16.Parse(s[3]));
Console.WriteLine(IP);

But your way is better I think... Thanks a lot

Upvotes: 0

Mikael
Mikael

Reputation: 982

IPAddress.Parse treats leading zeros as octal which is why you're getting an unexpected result.

This worked for me.

using System.Text.RegularExpressions;
..
..
    Console.WriteLine("ip address");
    string ip = Console.ReadLine();
    //Remove the leading zeroes with Regex...
    ip = Regex.Replace(ip, "0*([0-9]+)", "${1}");
    System.Net.IPAddress IP = System.Net.IPAddress.Parse(ip);
    Console.WriteLine(IP);

Upvotes: 2

Related Questions