< The System.net Tutorial | Main | C++, C# & VB .NET Services & Types Program Examples >

 


 

Chapter 6 Part 1:

Introduction to System.Net

 

 

What do we have in this chapter 6 Part 1?

  1. Introduction

  2. Layers of System.Net

  3. Basic Network Types and Services

  4. Using IP Addresses

  5. Working with Different Address Families

  6. Accessing Protected Resources

  7. Accessing DNS

 

 

Introduction

 

System.Net is the namespace in the Microsoft Windows .NET Framework that contains the core classes intended for building applications that communicate over a network. The types of functionality found in System.Net range from access to a raw socket to the ability to upload to and download from resources on the Internet. In addition to providing a language-independent, object-oriented way to access network resources, System.Net serves as the communication infrastructure for higher-level, distributed application programming models such as XML-based Web services and .NET Remoting.

 

Layers of System.Net

 

The System.Net classes can be divided into four layers, as depicted in Figure 6-1 and described in the following list.

 

The layers of System.Net namespaces

 

Figure 6-1: The layers of System.Net

 

1.      Basic network types and services: Fundamental types that are used for working with Internet Protocol (IP) addresses or non-IP network addresses such as Internetwork Packet Exchange (IPX). This layer also includes classes for performing Domain Name System (DNS) resolution.

2.      Socket-level APIs: A set of managed classes for performing network communication over a socket, such as sending and receiving data between two hosts.

3.      Application protocols: Classes intended to be used both on the client and on the middle tier. These classes are for protocols layered on top of the socket APIs, such as the Hypertext Transfer Protocol (HTTP) and the File Transfer Protocol (FTP).

4.      Protocol-independent request-response model: These classes provide a pattern that is used by request-response protocols for resolving Uniform Resource Identifiers (URIs) without requiring the developer to write protocol-specific code.

 

In this section, we’ll walk through each layer and introduce the most commonly used classes for each layer. The layers will be covered in-depth in the following chapters.

 

Basic Network Types and Services

 

Figure 6-2 contains the classes that make up the basic types and services included in System.Net. In the subsequent sections, we’ll look briefly at each of the basic types and services that are made accessible through System.Net. Although this section introduces the key types, most of them are covered in- depth in the chapters that follow.

 

Basic types and services provided by System.Net namespace

 

Figure 6-2: Basic types and services provided by System.Net

 

Using IP Addresses

 

The IPAddress type provides a class representation of an IP address. It includes methods that can be used to perform common operations on an IP address, such as parsing the address. The following code shows how you would parse an IP address.

 

C#

 

static void ParseIPAddress(string addressString)

{

    try

    {

        IPAddress address = IPAddress.Parse(addressString);

        Console.WriteLine("The address is " + address.ToString() + " and is of the family "

            + address.AddressFamily.ToString() + ".");

    }

    catch(Exception ex)

    {

        Console.WriteLine("Failure parsing " + addressString + ". " + ex.ToString());

    }

}

 

Visual Basic .NET

 

Sub ParseIPAddress(ByVal addressString As String)

    Try

        Dim address As IPAddress

        address = IPAddress.Parse(addressString)

 

        Console.WriteLine("The address is " & address.ToString _

            & " and is of the family " & _

            address.AddressFamily.ToString + ".")

 

    Catch ex As Exception

        Console.WriteLine("Failure parsing" & addressString & _

           ". " & ex.ToString)

    End Try

End Sub

 

Note that if an invalid IP address is specified in this case, IPAddress will throw a FormatException that should be handled by the application. The IPAddress class should be used for validation any time your application receives an IP address as input from a user, a configuration file, or another source. IPAddress also provides the ability to determine whether a particular address is a member of the Internet Protocol version 6 (IPv6) or the Internet Protocol version 4 (IPv4) address family. Finally, IPAddress contains a number of helper methods and fields, such as IPAddress.Any, IPAddress.IPv6Any, and IPAddress.IsLoopback. The Any fields can be used to indicate that the application should bind to a port that listens on all network interfaces of that address family. The IsLoopback method can be useful when validating whether a local loopback address is being used.

 

Working with Different Address Families

 

The System.Net.EndPoint class provides developers with a way to access resources through System.Net over protocols that belong to different address families that have different semantics at the addressing level. This functionality is useful when you need to write an application that talks over a non-IP protocol, such as AppleTalk, IPX, or infrared. Because IP-based protocols are the most commonly used on today’s networks, System.Net includes an IPEndPoint type in the .NET Framework. In the case of IPEndPoint, an end point is defined as an IP address and a port number. The .NET Compact Framework includes an IrDAEndPoint implementation of the EndPoint class that can be used for communicating with other nodes using infrared technologies. In the case of an IrDAEndPoint, an end point is defined as a device ID and a service name. Although most developers will simply work within the confines of the IP address family, this extensibility point is useful because the definition of an end point often varies from one address family to another.

 

 

Accessing Protected Resources

 

System.Net defines an ICredential interface and an associated NetworkCredential class that provide a means of specifying network credentials, such as a user name and a password in cases where network authentication is required when accessing a resource. These classes are mainly used in the context of the HTTP application protocol classes. However, in newer release of the .NET Framework, their use is likely to be expanded to include other socket-level authentication scenarios as well. The following code demonstrates how you can use the NetworkCredential class to authenticate with a remote resource.

 

C#

 

static void RequestProtectedResource(string resource)

{

    Console.WriteLine("Please enter your user name. ");

    string userName = Console.ReadLine();

 

    Console.WriteLine("Please enter your password.");

    string password = Console.ReadLine();

 

    WebClient client = new WebClient();

    client.Credentials = new NetworkCredential(userName, password);

    client.DownloadFile(resource, "page.htm");

}

 

Visual Basic .NET

 

Sub RequestProtectedResource(ByVal resource As String)

 

    Console.WriteLine("Please enter your user name. ")

    Dim userName As String

    userName = Console.ReadLine()

 

    Console.WriteLine("Please enter your password. ")

    Dim password As String

    password = Console.ReadLine()

 

    Dim client As New WebClient

    client.Credentials = New NetworkCredential(userName, password)

    client.DownloadFile(resource, "page.htm")

 

End Sub

 

Notice that in this code the credentials are obtained by prompting the user to enter them on the command line. System.Net also provides a way of using the default credentials of the account under which the application is running. You do so by setting the Credentials property on a class equal to CredentialCache.DefaultCredentials. Whenever possible, developers should use default credentials instead of prompting the user or reading credentials from some other source because default credentials are obtained through the security systems integrated into the underlying operating system.

 

Accessing DNS

 

DNS can be used to represent nodes on the network with human-readable names rather than IP addresses. For example, imagine trying to remember a string of characters such as www.contoso.com instead of a series of numbers such as 207.168.24.30. One feature provided by DNS is the ability to have multiple IP addresses assigned to one host name. You can even have different IP address types (for example, IPv4 and IPv6) assigned to the same host. It’s often useful to be able to resolve a name to the list of IP addresses associated with that name.

Access to DNS is enabled and controlled in System.Net through the Dns, DnsPermission, and IPHostEntry classes. DNS is covered in more detail in Chapter 7. The following example shows the basic steps involved in resolving a name and outputting the corresponding IP addresses to the console using System.Net.

 

C#

 

static void ResolveName(string name)

{

    try

    {

        IPHostEntry hostInfo = Dns.Resolve(name);

        foreach(IPAddress address in hostInfo.AddressList)

            Console.WriteLine(address.ToString());

    }

    catch(Exception ex)

    {

        Console.WriteLine(ex.ToString());

    }

}

 

Visual Basic .NET

 

Sub ResolveName(ByVal name As String)

    Try

        Dim hostInfo As IPHostEntry

        hostInfo = Dns.Resolve(name)

 

        Dim address As IPAddress

        For Each address In hostInfo.AddressList

            Console.WriteLine(address.ToString)

        Next address

 

    Catch ex As Exception

        Console.WriteLine(ex.ToString)

    End Try

End Sub

 

 

 


 

< The System.net Tutorial | Main | C++, C# & VB .NET Services & Types Program Examples >