Convert string to IP address format

24.6k Views Asked by At

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); 
5

There are 5 best solutions below

2
On

Something like this?
.Net 4.0

string str = string.Join(".", ips.Select(x => x.ToString()))

Earlier

string str = string.Join(".", ips.Select(x => x.ToString()).ToArray())

This says, join a string[] with . in between. The array is made up of ips, converted to string using ToString() and turned into a string[] using ToArray()

4
On

If it's an array:

string str = String.Format("{0:###}.{1:###}.{2:###}.{3:###}", ips[0], ips[1], ips[2], ips[3]);
1
On

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.)

3
On

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.

0
On

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....