Formatting IP address in C#
I used this hostInfo.AddressList
to get the machine开发者_运维问答 IP address. It returns it in the letter format, such as ff80::c9c9:b2af:aa0f:e2d2%12
, what I want is to format it to a IP address format (digits).
I am using C#, .net 3.5.
The format you gave is the correct way to represent an IPv6 address. There does not exist an A.B.C.D format to represent IPv6 addresses.
What's happening is you are getting a list of addresses both IPv4 and IPv6. You're looking for the IPv4 ones.
string GetFirstIPv4Address()
{
IPAddress[] addressList = Dns.GetHostAddresses(hostname);
foreach (IPAddress ip in addressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
//This is an IPv4 address
return ip.ToString();
}
}
return "127.0.0.1";
}
That is an ip address format, specifically an IPv6 IP address. It sounds like you want an IPv4 address, but IPv6 addresses cannot be down-converted into IPv4 addresses without knowing how your network is configured.
If your host has a v6 address, I suggest that you stick with it. You certainly shouldn't be trying to down-convert addresses at the application level.
精彩评论