MSDN Documentation

IPHostExtensions Class

Provides extension methods for working with IPHostEntry objects in the System.Net.IP namespace.

Introduction

The IPHostExtensions class is a static class that enhances the functionality of the IPHostEntry type. It offers a set of utility methods that simplify common tasks related to network host information, such as retrieving specific IP addresses or resolving hostnames.

Methods

  • static IPAddress GetIPv4Address(this IPHostEntry hostEntry)

    Retrieves the first IPv4 address from the host entry. If no IPv4 addresses are found, it returns null.

  • static IPAddress GetIPv6Address(this IPHostEntry hostEntry)

    Retrieves the first IPv6 address from the host entry. If no IPv6 addresses are found, it returns null.

  • static IEnumerable<IPAddress> GetAllIPv4Addresses(this IPHostEntry hostEntry)

    Returns all IPv4 addresses associated with the host entry.

  • static IEnumerable<IPAddress> GetAllIPv6Addresses(this IPHostEntry hostEntry)

    Returns all IPv6 addresses associated with the host entry.

  • static bool IsLocal(this IPHostEntry hostEntry)

    Checks if the host entry represents a local machine.

  • static bool IsLoopback(this IPHostEntry hostEntry)

    Checks if the host entry represents a loopback address.

Usage Example

Here's how you can use some of the extension methods from IPHostExtensions:

                
using System;
using System.Net;
using System.Linq;

// Assuming you have an IPHostEntry object, for example:
IPHostEntry hostInfo = Dns.GetHostEntry("www.example.com");

// Get the first IPv4 address
IPAddress ipv4 = hostInfo.GetIPv4Address();
if (ipv4 != null)
{
    Console.WriteLine($"IPv4 Address: {ipv4}");
}

// Get all IPv6 addresses
var ipv6Addresses = hostInfo.GetAllIPv6Addresses();
if (ipv6Addresses.Any())
{
    Console.WriteLine("IPv6 Addresses:");
    foreach (var ip in ipv6Addresses)
    {
        Console.WriteLine($"- {ip}");
    }
}

// Check if it's a local host
if (hostInfo.IsLocal())
{
    Console.WriteLine("This is a local host.");
}
                
            

Namespace

This class is part of the System.Net.IP namespace.

See Also