Convert string to IP address format

I am reading the IP numbers from the database in int format, but I want to show them in IP format, for example 000.000.000.000

Is it possible to use the String.Format method?

For instance,

string str = String.Format("{0:#,###,###.##}", ips); 
+3
source share
5 answers

Does not mean gravedig, but it will solve the problem.

IPAddress ip = IPAddress.Parse(IPStringHere);
+12
source

Are these 32-bit integers, each of which represents the entire IP address? If so...

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

(I don’t know why this constructor takes a lot of time, it will throw an exception if you exceed the range of UInt32, so UInt32 will be more suitable, in my opinion.)

+2
source

- ? .Net 4.0

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

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

a string[] . . ips, ToString() [] ToArray()

0
source

If it is an array:

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

I searched for the same answer ... but, seeing that no, I write myself.

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 .. no matter, not sure how you do it ....

0
source

Source: https://habr.com/ru/post/1793784/


All Articles