Tải bản đầy đủ - 0 (trang)
10-8. Resolve a Host Name to an IP Address

10-8. Resolve a Host Name to an IP Address

Tải bản đầy đủ - 0trang

CHAPTER 10 ■ NETWORKING



How It Works

On the Internet, the human-readable names that refer to computers are mapped to IP addresses, which

is what TCP/IP requires in order to communicate between computers. For example, the name

www.apress.com might be mapped to the IP address 66.211.109.45. It is not unusual for the IP address of

computers to change while their name remains constant, meaning that it is usually better to reference

computers with their name, not their IP address. To determine the current IP address for a given name,

the computer contacts a DNS server. The name or IP address of the DNS server contacted is configured

as part of a computer’s network configuration.

The entire process of name resolution is transparent if you use the System.Net.Dns class, which

allows you to retrieve the IP address for a host name by calling GetHostEntry.



■ Tip The Dns class also provides the BeginGetHostEntry and EndGetHostEntry methods, which allow you to

resolve IP addresses asynchronously. Also, the static method GetHostName returns the computer name of the local

machine.



The Code

The following example retrieves the IP addresses of all computers whose fully qualified domain names

are specified as command-line arguments:

using System;

using System.Net;

namespace Apress.VisualCSharpRecipes.Chapter10

{

class Recipe10_08

{

public static void Main(string[] args)

{

foreach (string comp in args)

{

try

{

// Retrieve the DNS entry for the specified computer.

IPAddress[] addresses = Dns.GetHostEntry(comp).AddressList;

// The DNS entry may contain more than one IP address. Iterate

// through them and display each one along with the type of

// address (AddressFamily).

foreach (IPAddress address in addresses)

{



505



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



Console.WriteLine("{0} = {1} ({2})",

comp, address, address.AddressFamily);

}

}

catch (Exception ex)

{

Console.WriteLine("{0} = Error ({1})", comp, ex.Message);

}

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter");

Console.ReadLine();

}

}

}



Usage

Running the example with the following command line:

recipe10-08 www.apress.com www.microsoft.com localhost somejunk

will produce output similar to the following. Notice that multiple IP addresses can be returned for some

host names.

www.apress.com = 65.19.150.100 (InterNetwork)

www.microsoft.com = 207.46.198.30 (InterNetwork)

www.microsoft.com = 207.46.20.30 (InterNetwork)

www.microsoft.com = 207.46.20.60 (InterNetwork)

www.microsoft.com = 207.46.18.30 (InterNetwork)

www.microsoft.com = 207.46.19.30 (InterNetwork)

www.microsoft.com = 207.46.19.60 (InterNetwork)

www.microsoft.com = 207.46.199.30 (InterNetwork)

www.microsoft.com = 207.46.198.60 (InterNetwork)

localhost = 127.0.0.1 (InterNetwork)

somejunk = Error (No such host is known)



506



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



10-9. Ping an IP Address

Problem

You want to check whether a computer is online and accessible and gauge its response time.



Solution

Send a ping message. This message is sent using the ICMP, accessible through the Send method of the

System.Net.NetworkInformation.Ping class.



■ Note The Ping class was introduced in the .NET Framework 2.0. To send a ping message in earlier versions of

the .NET Framework, you had to undertake significant effort to manually create an ICMP request message using

raw sockets and lengthy code.



How It Works

A ping message contacts a device at a specific IP address, passing it a test packet, and requests that the

remote device respond by echoing back the packet. To gauge the connection latency between two

computers, you can measure the time taken for a ping response to be received.



■ Caution Many commercial web sites do not respond to ping requests because they represent an unnecessary

processing overhead and are often used in denial-of-service attacks. The firewall that protects the site will usually

filter them out before they reach the specified destination. This will cause your ping request to time out.



The Ping class allows you to send ping messages using the Send method. The Send method provides

a number of overloads, which allow you to specify some or all of the following:





The IP address or host name of the target computer. You can specify this as a

string or a System.Net.IPAddress object.







The number of milliseconds to wait for a response before the request times out

(specified as an int) with the default set to 5,000.







A byte array of up to 65,500 data bytes that is sent with the ping request and that

should be returned in the response.







A System.Net.NetworkInformation.PingOptions object that specifies time-to-live

and fragmentation options for the transmission of the ping message.



507



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



The Send method will return a System.Net.NetworkInformation.PingReply object. The Status

property of the PingReply will contain a value from the System.Net.NetworkInformation.IPStatus

enumeration from which you can determine the result of the ping request. The most common values

will be Success and TimedOut. If the host name you pass to the Send method cannot be resolved, Send will

throw an exception, but you must look at the InnerException to determine the cause of the problem.

The Ping class also provides a SendAsync method that performs the ping request using a thread-pool

thread so that the calling thread does not block. When the ping is finished or fails because of a timeout,

the thread raises the PingCompleted event on the Ping object, which you can handle using a method that

matches the signature of the System.Net.NetworkInformation.PingCompletedEventHandler delegate.

However, the Ping object can handle only a single concurrent request; otherwise, it will throw a

System.InvalidOperationException.



■ Tip The Ping class derives from System.ComponentModel.Component, so you can add it to the Visual Studio

Form Designer Toolbox in order to allow you to easily set the properties or define the event handlers in a Windows

Forms–based application.



The Code

The following example pings the computers whose domain names or IP addresses are specified as

command-line arguments:

using System;

using System.Net.NetworkInformation;

namespace Apress.VisualCSharpRecipes.Chapter10

{

class Recipe10_09

{

public static void Main(string[] args)

{

// Create an instance of the Ping class.

using (Ping ping = new Ping())

{

Console.WriteLine("Pinging:");

foreach (string comp in args)

{

try

{

Console.Write("

{0}...", comp);

// Ping the specified computer with a timeout of 100 ms.

PingReply reply = ping.Send(comp, 100);



508



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

10-8. Resolve a Host Name to an IP Address

Tải bản đầy đủ ngay(0 tr)

×