IPAddress Class

Represents an Internet Protocol (IP) address.

This class is immutable. Once created, its value cannot be changed.

Constructors

Properties

Methods

Fields

Example

The following code example demonstrates how to create and use IPAddress objects.

using System;
using System.Net;

public class IPAddressExample
{
    public static void Main(string[] args)
    {
        // Create an IPv4 address
        IPAddress ipv4Address = IPAddress.Parse("192.168.1.1");
        Console.WriteLine($"IPv4 Address: {ipv4Address}");
        Console.WriteLine($"Address Family: {ipv4Address.AddressFamily}");
        Console.WriteLine($"Is IPv4 Loopback: {ipv4Address.IsLoopback}");

        Console.WriteLine();

        // Create an IPv6 address
        IPAddress ipv6Address = IPAddress.Parse("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
        Console.WriteLine($"IPv6 Address: {ipv6Address}");
        Console.WriteLine($"Address Family: {ipv6Address.AddressFamily}");
        Console.WriteLine($"Is IPv6 Loopback: {ipv6Address.IsLoopback}");

        Console.WriteLine();

        // Using TryParse
        IPAddress parsedAddress;
        if (IPAddress.TryParse("10.0.0.1", out parsedAddress))
        {
            Console.WriteLine($"Successfully parsed: {parsedAddress}");
        }
        else
        {
            Console.WriteLine("Failed to parse IP address.");
        }

        // Accessing static properties
        Console.WriteLine($"Any IP Address: {IPAddress.Any}");
        Console.WriteLine($"Loopback IP Address: {IPAddress.Loopback}");
    }
}

Remarks

The IPAddress class is used to represent an IP address (either IPv4 or IPv6). It is fundamental for network programming in .NET, allowing applications to specify which network interfaces to listen on or which remote hosts to connect to.

Key features include:

  • Immutable: Once an IPAddress object is created, its value cannot be changed.
  • IPv4 and IPv6 Support: The class handles both IPv4 and IPv6 address families.
  • Static Properties: Provides convenient access to commonly used IP addresses like Any, Loopback, and Broadcast.
  • Parsing: Methods like Parse and TryParse allow for easy conversion of string representations to IPAddress objects.

When dealing with IPv6 addresses, it's important to be aware of scope identifiers, especially for link-local addresses. The ScopeId property and related constructors are used for this purpose.