IP Tools

This section provides an overview of the utilities and helper classes available within the System.Net.IP namespace for working with IP addresses and related network information.

Overview

The .NET Framework offers a robust set of classes for handling Internet Protocol (IP) addressing. These tools are essential for building network-aware applications, enabling communication between devices, and managing network configurations programmatically. The primary classes in this area include:

Key Functionality

The IP tools in .NET facilitate a variety of operations, including:

IPAddress Class

Description

The IPAddress class is the cornerstone for representing IP addresses. It supports both IPv4 and IPv6 formats, allowing for modern network compatibility.

Common Properties and Methods

  • AddressFamily: Gets the address family (IPv4 or IPv6).
  • IsIPv4MappedToIPv6: Checks if the address is an IPv4-mapped IPv6 address.
  • ToString(): Returns a string representation of the IP address.
  • Parse(string ipString): Parses a string representation of an IP address.
  • TryParse(string ipString, out IPAddress address): Tries to parse a string representation of an IP address without throwing an exception.

Example


using System.Net;

// Create an IPv4 address
IPAddress ipv4Addr = IPAddress.Parse("192.168.1.100");
Console.WriteLine($"IPv4 Address: {ipv4Addr}");
Console.WriteLine($"Address Family: {ipv4Addr.AddressFamily}");

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

// Parse from a string safely
if (IPAddress.TryParse("10.0.0.5", out IPAddress parsedAddr))
{
    Console.WriteLine($"Successfully parsed: {parsedAddr}");
}
                    

IPEndPoint Class

Description

IPEndPoint combines an IPAddress with a port number, defining a specific network endpoint for communication (e.g., a server listening on a particular port).

Common Properties and Methods

  • Address: Gets or sets the IP address.
  • Port: Gets or sets the port number.
  • Create(long socketAddress): Creates an IPEndPoint from a socket address structure.
  • ToString(): Returns a string representation in the format "IPAddress:Port".

Example


using System.Net;

IPAddress ipAddress = IPAddress.Loopback; // 127.0.0.1 or ::1
int port = 8080;

IPEndPoint endpoint = new IPEndPoint(ipAddress, port);
Console.WriteLine($"Endpoint: {endpoint}");
Console.WriteLine($"Address: {endpoint.Address}");
Console.WriteLine($"Port: {endpoint.Port}");
                    

Best Practices