开发者

Convert string to IP address format

I'm reading IP address number开发者_StackOverflow中文版s 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); 


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.


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


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


If it's an array:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜