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.)
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With