Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

13.2. Converting a Hostname to an IP Address

Problem

You have a string representation of a host (such as www.oreilly.com), and you need to obtain the IP address from this hostname.

Solution

Use the Dns.Resolve method to get the IP addresses. In the following code, a hostname is provided to the Resolve method that returns an IPHostEntry from which a string of addresses can be constructed and returned:

using System;
using System.Net;
using System.Text;

// ...

public static string HostName2IP(string hostname)
{
    // resolve the hostname into an iphost entry using the dns class
    IPHostEntry iphost = System.Net.Dns.Resolve(hostname);
    // get all of the possible IP addresses for this hostname
    IPAddress[] addresses = iphost.AddressList;
    // make a text representation of the list
    StringBuilder addressList = new StringBuilder( );
    // get each ip address
    foreach(IPAddress address in addresses)
    {
        // append it to the list
        addressList.Append("IP Address: ");
        addressList.Append(address.ToString( ));
        addressList.Append(";");
    }
    return addressList.ToString( );
}

// ...

// writes "IP Address: 208.201.239.37;IP Address: 208.201.239.36;"
Console.WriteLine(HostName2IP("www.oreilly.com"));

Discussion

An IPHostEntry can associate multiple IP addresses with a single hostname via the AddressList property. AddressList is an array of IPAddress objects, each of which holds a single IP address. Once the IPHostEntry is resolved, the AddressList can be looped over using foreach to create a string that shows all of ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata