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);
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);
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.)
Usomething
(or their alias usomething
like uint
) types is frowned in .NET. It isn't CLS compliamnt, because some languages don't distinguish between signed and unsigned (and have only, normally, the signed version). IPAddress
is a .NET framework class, so it must be compatible with all the languages, so no UInt32
and yes to long
–
Surfperch 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....
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()
If it's an array:
string str = String.Format("{0:###}.{1:###}.{2:###}.{3:###}", ips[0], ips[1], ips[2], ips[3]);
int
, or is it a string or what? –
Surfperch © 2022 - 2024 — McMap. All rights reserved.