Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to IP address format

I'm reading IP address numbers from database in a int format but I want to show them in IP format like 000.000.000.000

Is it possible using the String.Format method?

For e.g.:

string str = String.Format("{0:#,###,###.##}", ips); 
like image 367
Noname Avatar asked Feb 22 '11 06:02

Noname


3 Answers

If you use the IPAddress object in the System.Net namespace to parse your address in as follows:

IPAddress ip = IPAddress.Parse(IPStringHere);

then use the "ToString()" method on that object:

string outputString = ip.ToString();

you can get a string that shows the IP address provided in the format you require using integers and full stops.

The IPAddress parsing routine will take a string IP address and it will also take an int/long int format address too allowing you to parse both formats.

As a bonus if your use "TryParse" and put your conversion in an if block, you can also test to see if the input format results in a correct IP address before returning the string, handy for input validation.

like image 70
Louis Getz Avatar answered Nov 05 '22 21:11

Louis Getz


Are these 32-bit integers that each represent the entire IP address? If so...

IPAddress ip = new IPAddress((long)ips);
return ip.ToString();

(I don't know why that constructor takes a long, it'll throw an exception if you exceed the range of a UInt32, so a UInt32 would be more appropriate in my opinion.)

like image 2
David Yaw Avatar answered Nov 05 '22 22:11

David Yaw


I came looking for the same answer .. but seeing as there are non I write my self.

private string padIP(string ip)
{
    string output = string.Empty;
    string[] parts = ip.Split('.');
    for (int i = 0; i < parts.Length; i++)
    {
        output += parts[i].PadLeft(3, '0');
        if (i != parts.Length - 1)
            output += ".";
    }
    return output;
}

edit: ah i see in int format .. never mind, not sure how you would do that....

like image 1
Chris Avatar answered Nov 05 '22 20:11

Chris