760 likes | 920 Views
Network Programming. Chapter 3: Network Programming in .NET. Topics. System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions. System.Net Classes. Name Lookup
E N D
Network Programming Chapter 3: Network Programming in .NET
Topics • System.Net Classes Overview • Working with URIs • IP Addresses • Dns Class • Requests and Responses • Using a Web Proxy • Authentication • Permissions
System.Net Classes • Name Lookup • Dns Class used to get host name from IP address or IP address from a DNS host name • DnsPermissionAttribute is an attribute class to mark assemblies, classes or methods that need permission to required for name lookups • DnsPermission class represents the permission required for name lookups
System.Net Classes • IP Addresses • IP addresses are handled within the class IPAddress. A single host can have multiple IP addresses and alias names. All this information is contained within the class IPHostEntry. The Dns class returns an object of type IPHostEntry when you do a name lookup «utility» Dns IPHostEntry IPAddress
System.Net Classes • Authentication and Authorization • AuthenticationManager class has static methods to authenticate the client user «interface» IAuthenticationModule «utility» AuthenticationManager Returns «interface» ICredentials AuthenticationModule Returns Authorization Caches CredentialCache NetworkCredential
System.Net Classes • Requests and Responses • HttpVersion class is used to specify the HTTP version. • HttpWebRequest and HttpWebResponse classes have a ProtocolVersion property • HttpVersion.Version10 • HttpVersion.Version11 • WebClient class makes it easy to upload files to, and download files from a server WebResponse WebRequest FileWebResponse HttpWebResponse HttpWebRequest FileWebRequest
System.Net Classes • Connection Management • ServicePoint class • URI to resource • Handles multiple connections • ServicePointManager class • Manages ServicePoints • Create new ServicePoints • Find existing ServicePoints «utility» ServicePointManager manages ServicePoint
System.Net Classes • Cookies • Sets of data stored on the client side • Used by the server to remember information between requests • Web browser manages acceptance, storage and sending of cookies • CookieCollection class • Cookie is represented in the Cookie class • Note: Cookies are sent within the header of the HTTP protocol
System.Net Classes • Cookies HttpWebResponse HttpWebRequest Cookies CookieContainer CookieCollection Cookie CookieContainer
System.Net Classes • Proxy Server • Used in the network environment to direct connection to the Internet through a single system (or multiple systems depending on the network size) • Can cache pages that are requested by users • WebProxy class • Used to define the proxy server that should be consulted for Internet requests • GlobalProxySelection class is used to define a default proxy server that should be used for all requests if not specified otherwise for a specific request «utility» GlobalProxySelection WebProxy
System.Net Classes • Sockets • Offer more features, flexibility and complexity than web classes • System.Net.Sockets namespace • Allows connectionless and connection-orientated programming • Allows different protocols
Topics • System.Net Classes Overview • Working with URIs • IP Addresses • Dns Class • Requests and Responses • Using a Web Proxy • Authentication • Permissions
Working with URIs • URI = Uniform Resource Identifier • URI can access • Web pages • FTP services • Web services • Local files • URI also known as • URL = Uniform Resource Locator • URN = Uniform Resource Name • A URN is a standardized URI and is used to specify a resource independent of its network location
Working with URIs • Internet standardSTD 66 (also RFC 3986) defines the generic syntax to be used in all URI schemes. Every URI is defined as consisting of four parts, as follows: <scheme name> : <hierarchical part> [ ? <query> ] [ # <fragment> ] • The scheme name consist of a letter followed by any combination of letters, digits, and the plus ("+"), period ("."), or hyphen ("-") characters; and is terminated by a colon (":"). • The hierarchical part of the URI is intended to hold identification information hierarchical in nature. Usually this part begins with a double forward slash ("//"), followed by an authority part and an optional path. The authority part holds an optional user information part terminated with "@" (e.g. username:password@), a hostname (i.e. domain name or IP address), and an optional port number preceded by a colon ":". The path part is a sequence of segments (conceptually similar to directories, though not necessarily representing them) separated by a forward slash ("/"). Each segment can contain parameters separated from it using a semicolon (";"), though this is rarely used in practice. • The query is optional part separated with a question mark, which contains additional identification information which is not hierarchical in nature. Its syntax is not generically defined, but is commonly organized as a sequence of <key>=<value> pairs separated by an ampersand, e. g. key1=value1&key2=value2&key3=value3. • The fragment is an optional part separated from the front parts by a hash ("#"). It holds additional identifying information which allows indirect identification of a secondary resource, e.g. a section heading in an article identified by the remainder of the URI.
Working with URIs • Examples • The following are two example URIs and their component parts (taken from STD 66): foo://example.com:8042/over/there?name=ferret#nose fragment query path Authority (server & port) scheme urn:example:animal:ferret:nose
Working with URIs • Reserved URI characters ; / ? : @ & = + $ , • URI Class • In the System namespace • Has properties and methods for parsing, comparing and combining URIs
Working with URIs • Uri Class • Constructing Uri Objects • Create a Uri object by passing a URI string to the constructor • Uri uri = new Uri(http://msdn.microsoft.com/code/default.asp); • Create a new Uri object by combining a known base Uri with a relative URI • Uri baseUri = new Uri(http://msdn.microsoft.com); • Uri newUri = new Uri(baseUri, “code/default.asp”); • Commonly Used Schemes • Checking for a Valid Host Name and Scheme
Working with URIs • Uri Class • Commonly Used Schemes
Working with URIs • Uri Class • Checking for a valid host name and field • Uri.CheckSchemeName returns true if the scheme name is valid • Uri.CheckHostName checks the host name and returns the host type (UriHostNameType enumeration)
Working with URIs • Modifying URIs with the UriBuilder Class • The properties of a URI class are read-only (cannot be edited after instantiation) • To change values in a URI dynamically, you can use the UriBuilder class • UriBuilder class similar to Uri class
Working with URIs • Absolute and Relative URIs • Absolute URI • Starts with scheme, host name and optional port number • Can have path • Relative URI • Defined only with a path • Requires an absolute URI as its base (to know exact resource location) • Shorter than absolute URIs • If you have one URI in use, a relative URI is sufficient to access another resource from the same host • URI Class • only stores absolute URIs • MakeRelativeUri() method creates a relative URI out of an absolute one
URIClassDemo Uri baseUri = new Uri("http://www.gotdotnet.com"); Uri resource1 = new Uri(baseUri, "team/libraries"); Uri resource2 = new Uri(resource1, "/userarea/default.aspx"); Console.WriteLine("Showing the path from one URI to another..."); Console.WriteLine("Resource 1: "+resource1.AbsoluteUri); Console.WriteLine("Resource 2: "+resource2.AbsoluteUri); Console.ReadLine(); Console.WriteLine("Making a relative URI (returned as a string) from absolute URIs"); resource1 = new Uri("http://www.gotdotnet.com/userarea/default.aspx"); resource2 = new Uri("http://www.gotdotnet.com/team/libraries/"); Console.WriteLine(resource1.MakeRelativeUri(resource2)); Console.WriteLine(resource2.MakeRelativeUri(resource1)); Uri resource3 = new Uri("http://msdn.microsoft.com/vstudio/default.asp"); Console.WriteLine(resource2.MakeRelativeUri(resource3)); Console.ReadLine();
Topics • System.Net Classes Overview • Working with URIs • IP Addresses • Dns Class • Requests and Responses • Using a Web Proxy • Authentication • Permissions
IP Addresses • TCP/IP network uses IP addresses • IPv4 • 32 bits • Dotted quad notation • IPAddress class • System.Net namespace • Encapsulates an IP address • Supports conversion functionality (network to host byte order and vice versa)
IP Addresses • Predefined Addresses See IPAddressClassDemo
IP Addresses • Host or Network Byte Order • Little endian • Least significant byte stored at lower memory address • Intel-compatible CPUs • Big endian • Motorola CPUs • Network byte order • Big endian • Need to convert Intel-compatible IP addresses to network byte order • IPAddress.NetworkToHostOrder (Converts a number from network byte order to host byte order. ) • IPAddress.HostToNetworkOrder (Converts a value from host byte order to network byte order. ) • If you do not plan to communicate with systems of a different CPU architecture, there’s no need to check for the byte order
Topics • System.Net Classes Overview • Working with URIs • IP Addresses • Dns Class • Requests and Responses • Using a Web Proxy • Authentication • Permissions
Dns Class • To connect to a server, the IP address of the server is needed • DNS server resolves names to IP addresses • Use the Dns class to resolve domain names to IP addresses
Dns Class • Resolving a Name to an IP Address • IP address from a host name • Dns.Resolve • For a single host name, multiple IP addresses can be configured • Resolve returns not only an IP address, but also an IPHostEntry • IPHostEntry holds an array of addresses, alias names and the host name itself
Topics • System.Net Classes Overview • Working with URIs • IP Addresses • Dns Class • Requests and Responses • Using a Web Proxy • Authentication • Permissions
How Is an IP Address Resolved? • Ways in which IP addresses can be resolved • HOST file has a mapping from an IP address to the name of the host with optional additional alias names. <windir>\system32\drivers\etc. (early version of TCP/IP) • DNS introduced after HOST system. Getting the host name from an IP address is known as reverse lookup. New IP addresses are only added to the DNS server. Client systems only need be aware of the DNS server • Dynamic Host Configuration Protocol (DHCP) may be used. Client PCs may now have a dynamic IP address. Introduction of dynamic DNS • If the DNS fails, NetBIOS naming mechanisms are used to get an IP address
How Is an IP Address Resolved? • NetBIOS Host Names • NBT (NetBIOS over TCP/IP) • Normally, the NetBIOS name is the same as the DNS name without the domain name extension • For NetBIOS name resolution, an LMHOSTS file is used • If the name cannot be resolved with the LMHOSTS file, the NetBIOS name resolution depends on the NetBIOS node types
How is an IP Address Resolved? • NetBIOS node types
Resolving the IP Address Asynchronously using System; using System.Collections.Generic; using System.Text; using System.Net; namespace AsyncDnsDemo { class Program { private static string hostName = "www.nmmu.ac.za"; static void Main(string[] args) { if (args.Length != 0) hostName = args[0]; Dns.BeginGetHostEntry(hostName, new AsyncCallback(DnsLookupCompleted), null); Console.WriteLine("Waiting for the results..."); Console.ReadLine(); }
Resolving the IP Address Asynchronously private static void DnsLookupCompleted(IAsyncResult ar) { IPHostEntry entry = Dns.EndGetHostEntry(ar); Console.WriteLine("IP Addresses for {0}", hostName); foreach (IPAddress address in entry.AddressList) Console.WriteLine(address.ToString()); Console.WriteLine(); if (entry.Aliases.Length > 0) { Console.WriteLine("Alias names:"); foreach (string aliasName in entry.Aliases) Console.WriteLine(aliasName); } else Console.WriteLine("Address does not have any aliases."); Console.WriteLine(); Console.WriteLine("And the real host name: {0}", entry.HostName); } } }
Topics • System.Net Classes Overview • Working with URIs • IP Addresses • Dns Class • Requests and Responses • Using a Web Proxy • Authentication • Permissions
Requests and Responses • After the name of the host is resolved, the client and server can start communicating • The server creates a socket and listens for incoming clients, the client connects to the server and then the client and the server can send and receive data
Requests and Responses using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace RqstAndResponseDemo { class Program { static void Main(string[] args) { Uri uri = new Uri("http://www.nmmu.ac.za"); WebRequest request = WebRequest.Create(uri); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } response.Close(); reader.Close(); Console.ReadLine(); } } }
Requests and Responses • Web Request and Web Response • Base classes • Abstract classes • Web Response • Used to read data from the server • GetResponse() method returns an object of the WebResponse class
Requests and Responses • Pluggable Protocols • WebRequest class is abstract • WebRequest.Create creates a child class of WebRequest only • Passing an HTTP request to the WebRequest.Create method creates an HttpWebRequest object • Passing a file scheme creates a FileWebRequest object • Schemes to use: • http • https • file
Pluggable Protocols • http, https & file schemes are pre-defined in the machine.config file • <windows>\Microsoft.NET\Framework\<version>\CONFIG <configuration> <system.net> <webRequestModules> <clear /> <add prefix="https:" type="System.Net.HttpRequestCreator, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <add prefix="http:" type="System.Net.HttpRequestCreator, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <add prefix="file:" type="System.Net.FileWebRequestCreator, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <add prefix="ftp:" type="System.Net.FtpWebRequestCreator, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </webRequestModules> </system.net> </configuration>