Utility Classes


This section covers a couple of utility classes to make Web programming easier when dealing with URIs and IP addresses.

URIs

Uri and UriBuilder are two classes in the System (not System.Net) namespace, and they are both intended to represent a URI. UriBuilder allows you to build a URI given the strings for the component parts, and the Uri class allows you to parse, combine, and compare URIs.

For the Uri class, the constructor requires a completed URI string:

 Uri MSPage = new  Uri("http://www.Microsoft.com/SomeFolder/SomeFile.htm?Order=true"); 

The class exposes a large number of read-only properties. A Uri object is not intended to be modified once it has been constructed:

 string Query = MSPage.Query;                   // Order=true; string AbsolutePath = MSPage.AbsolutePath;     // SomeFolder/SomeFile.htm string Scheme = MSPage.Scheme;                 // http int Port = MSPage.Port;                        // 80 (the default for http) string Host = MSPage.Host;                     // www.Microsoft.com bool IsDefaultPort = MSPage.IsDefaultPort;     // true since 80 is default 

URIBuilder, on the other hand, implements fewer properties; just enough to allow you to build up a complete URI. These properties are read-write.

You can supply the components to build up a URI to the constructor:

 Uri MSPage = new  UriBuilder("http", "www.Microsoft.com", 80, "SomeFolder/SomeFile.htm"); 

Or you can build the components by assigning values to the properties:

 UriBuilder MSPage = new UriBuilder(); MSPage.Scheme ="http"; MSPage.Host = "www.Microsoft.com"; MSPage.Port = 80; MSPage.Path = "SomeFolder/SomeFile.htm"; 

Once you have completed initializing the UriBuilder, you can obtain the corresponding Uri object with the Uri property:

 Uri CompletedUri = MSPage.Uri; 

IP Addresses and DNS Names

On the Internet you identify servers as well as clients by IP address or host name (also referred to as a DNS name). Generally speaking, the host name is the human-friendly name that you type in a Web browser window, such as www.wrox.com or www.microsoft.com. An IP address, on the other hand, is the identifier computers use to identify each other. IP addresses are the identifiers used to ensure Web requests and responses reach the appropriate machines. It is even possible for a computer to have more than one IP address.

For host names to work, you must first send a network request to translate the host name into an IP address, a task carried out by one or more DNS servers.

A DNS server stores a table mapping host names to IP addresses for all the computers it knows about, as well as the IP addresses of other DNS servers to look up the host names it does not know about. Your local computer should always know about at least one DNS server. Network administrators configure this information when a computer is set up.

Before sending out a request, your computer will first ask the DNS server to tell it the IP address corresponding to the host name you have typed in. Once armed with the correct IP address, the computer can address the request and send it over the network. All of this work normally happens behind the scenes while the user is browsing the Web.

.NET classes for IP addresses

The .NET Framework supplies a number of classes that are able to assist with the process of looking up IP addresses and finding out information about host computers.

IPAddress

IPAddress represents an IP address. The address itself is available as the GetAddressBytes property and may be converted to a dotted decimal format with the ToString() method. IPAddress also implements a static Parse() method, which effectively performs the reverse conversion of ToString() — converting from a dotted decimal string to an IPAddress:

 IPAddress ipAddress = IPAddress.Parse("234.56.78.9"); byte[] address = ipAddress.GetAddressBytes(); string ipString = ipAddress.ToString(); 

In this example, the byte integer address is assigned a binary representation of the IP address, and the string ipString is assigned the text "234.56.78.9".

IPAddress also provides a number of constant static fields to return special addresses. For example, the Loopback address allows a machine to send messages to itself, whereas the Broadcast address allows multicasting to the local network:

 // The following line will set loopback to "127.0.0.1".  // the loopback address indicates the local host.  string loopback = IPAddress.Loopback.ToString(); // The following line will set broadcast address to "255.255.255.255".  // the broadcast address is used to send a message to all machines on  // the local network.  string broadcast = IPAddress.Broadcast.ToString(); 

IPHostEntry

The IPHostEntry class encapsulates information relating to a particular host computer. This class makes the host name available via the HostName property (which returns a string), and the AddressList property returns an array of IPAddress objects. You are going to use the IPHostEntry class in the in next example: DNSLookupResolver.

The Dns class is able to communicate with your default DNS server to retrieve IP addresses. The two important (static) methods are Resolve(), which uses the DNS server to obtain the details of a host with a given host name, and GetHostByAddress(), which also returns details of the host but this time using the IP address. Both methods return an IPHostEntry object:

 IPHostEntry wroxHost = Dns.Resolve("www.wrox.com");  IPHostEntry wroxHostCopy = Dns.GetHostByAddress("208.215.179.178"); 

In this code, both IPHostEntry objects will contain details of the Wrox.com servers.

Dns

The Dns class differs from the IPAddress and IPHostEntry classes because it has the ability to actually communicate with servers to obtain information. In contrast, IPAddress and IPHostEntry are more along the lines of simple data structures with convenient properties to allow access to the underlying data.

The DnsLookup example

The DNS and IP-related classes are illustrated with an example that looks up DNS names: DnsLookup (see Figure 35-12).

image from book
Figure 35-12

This sample application simply invites the user to type in a DNS name using the main text box. When the user clicks the Resolve button, the sample uses the Dns.Resolve() method to retrieve an IPHostEntry reference and display the host name and IP addresses. Note how the host name displayed may be different from the name typed in. This can occur if one DNS name (www.microsoft.com) simply acts as a proxy for another DNS name (www.microsoft.com.nsatc.net).

The DnsLookup application is a standard C# Windows application. The controls are added as shown in Figure 35-12, giving them the names txtBoxInput, btnResolve, txtBoxHostName, and listBoxIPs, respectively. Then you simply add the following method to the Form1 class as the event handler for the buttonResolve click event:

 void btnResolve_Click (object sender, EventArgs e) { try { IPHostEntry iphost = Dns.Resolve(txtBoxInput.Text); foreach (IPAddress ip in iphost.AddressList) { string ipaddress = ip.AddressFamily.ToString(); listBoxIPs.Items.Add(ipaddress); listBoxIPs.Items.Add("   " + ip.ToString()); } txtBoxHostName.Text = iphost.HostName; } catch(Exception ex) { MessageBox.Show("Unable to process the request because " + "the following problem occurred:\n" + ex.Message, "Exception occurred"); } } 

Notice that in this code you are careful to trap any exceptions. An exception might occur if the user types in an invalid DNS name or if the network is down.

After retrieving the IPHostEntry instance, you use the AddressList property to obtain an array containing the IP addresses, which you then iterate through with a foreach loop. For each entry, you display the IP address as an integer and as a string, using the IPAddress.AddressFamily.ToString() method.




Professional C# 2005
Pro Visual C++ 2005 for C# Developers
ISBN: 1590596080
EAN: 2147483647
Year: 2005
Pages: 351
Authors: Dean C. Wills

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net