public override string ToString()
Description
Returns a string representation of the IP address.
This method returns the IP address in a standard dotted-decimal format (for IPv4) or in the standard IPv6 representation.
Returns
| Type | Description |
|---|---|
string |
A string representation of the IP address. |
Remarks
The ToString() method is useful for displaying IP addresses in user interfaces or for logging purposes. It handles the formatting for both IPv4 and IPv6 addresses correctly.
For IPv4 addresses, it will return a string in the format "a.b.c.d", where a, b, c, and d are the decimal representations of the four bytes of the IP address.
For IPv6 addresses, it will return a string in the standard IPv6 format, which may include abbreviations for consecutive zeros.
Examples
The following example demonstrates how to use the ToString() method to get string representations of IPv4 and IPv6 addresses.
using System;
using System.Net;
public class IPAddressToStringExample
{
public static void Main(string[] args)
{
// IPv4 Address
IPAddress ipv4Address = IPAddress.Parse("192.168.1.1");
string ipv4String = ipv4Address.ToString();
Console.WriteLine($"IPv4 Address String: {ipv4String}"); // Output: IPv4 Address String: 192.168.1.1
// IPv6 Address
IPAddress ipv6Address = IPAddress.Parse("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
string ipv6String = ipv6Address.ToString();
Console.WriteLine($"IPv6 Address String: {ipv6String}"); // Output: IPv6 Address String: 2001:db8:85a3::8a2e:370:7334
// IPv6 Address with IPv4-mapped format
IPAddress mappedV6Address = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 192, 168, 1, 1 });
string mappedV6String = mappedV6Address.ToString();
Console.WriteLine($"Mapped IPv6 Address String: {mappedV6String}"); // Output: Mapped IPv6 Address String: ::ffff:192.168.1.1
}
}