Top Banner
Network Programming Chapter 3: Network Programming in .NET
76
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Network Programming Chapter 3: Network Programming in.NET.

Network Programming

Chapter 3: Network Programming in .NET

Page 2: 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

Page 3: Network Programming Chapter 3: Network Programming in.NET.

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

Page 4: Network Programming Chapter 3: Network Programming in.NET.

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»

DnsIPHostEntry

IPAddress

Page 5: Network Programming Chapter 3: Network Programming in.NET.

System.Net Classes

• Authentication and Authorization– AuthenticationManager class has static methods to

authenticate the client user

«utility»AuthenticationManager

«interface»IAuthenticationModule

Authorization

AuthenticationModule«interface»

ICredentials

CredentialCache NetworkCredential

Returns

Returns

Caches

Page 6: Network Programming Chapter 3: Network Programming in.NET.

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

WebRequest

HttpWebRequest FileWebRequest

WebResponse

HttpWebResponse FileWebResponse

Page 7: Network Programming Chapter 3: Network Programming in.NET.

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

ServicePointmanages

Page 8: Network Programming Chapter 3: Network Programming in.NET.

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

Page 9: Network Programming Chapter 3: Network Programming in.NET.

System.Net Classes

• Cookies

HttpWebRequest

CookieContainer CookieCollection

CookieContainer

HttpWebResponse

Cookies

Cookie

Page 10: Network Programming Chapter 3: Network Programming in.NET.

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

Page 11: Network Programming Chapter 3: Network Programming in.NET.

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

Page 12: 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

Page 13: Network Programming Chapter 3: Network Programming in.NET.

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

Page 14: Network Programming Chapter 3: Network Programming in.NET.

Working with URIs• Internet standard STD 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.

Page 15: Network Programming Chapter 3: Network Programming in.NET.

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

urn:example:animal:ferret:nose

scheme Authority (server & port) path query fragment

Page 16: Network Programming Chapter 3: Network Programming in.NET.

Working with URIs

• Reserved URI characters; / ? : @ & = + $ ,

• URI Class– In the System namespace– Has properties and methods for parsing,

comparing and combining URIs

Page 17: Network Programming Chapter 3: Network Programming in.NET.

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

Page 18: Network Programming Chapter 3: Network Programming in.NET.

Working with URIs

• Uri Class– Commonly Used Schemes

Name Description

UriSchemeFile Specifies that the URI is a pointer to a file. This field is read-only.

UriSchemeFtpSpecifies that the URI is accessed through the File Transfer Protocol (FTP). This field is read-

only.

UriSchemeGopher Specifies that the URI is accessed through the Gopher protocol. This field is read-only.

UriSchemeHttpSpecifies that the URI is accessed through the Hypertext Transfer Protocol (HTTP). This field

is read-only.

UriSchemeHttpsSpecifies that the URI is accessed through the Secure Hypertext Transfer Protocol (HTTPS).

This field is read-only.

UriSchemeMailtoSpecifies that the URI is an e-mail address and is accessed through the Simple Mail

Transport Protocol (SMTP). This field is read-only.

UriSchemeNetPipeSpecifies that the URI is accessed through the NetPipe scheme of the "Indigo" system. This

field is read-only.

UriSchemeNetTcpSpecifies that the URI is accessed through the NetTcp scheme of the "Indigo" system. This

field is read-only.

UriSchemeNewsSpecifies that the URI is an Internet news group and is accessed through the Network News

Transport Protocol (NNTP). This field is read-only.

UriSchemeNntpSpecifies that the URI is an Internet news group and is accessed through the Network News

Transport Protocol (NNTP). This field is read-only.

Page 19: Network Programming Chapter 3: Network Programming in.NET.

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)

Page 20: Network Programming Chapter 3: Network Programming in.NET.

Working with URIs

UriHostNameType enumerationMember name Description

Basic The host is set, but the type cannot be determined. 

Dns The host name is a domain name system (DNS) style host name. 

IPv4 The host name is an Internet Protocol (IP) version 4 host address. 

IPv6 The host name is an Internet Protocol (IP) version 6 host address. 

Unknown The type of the host name is not supplied. 

Page 21: Network Programming Chapter 3: Network Programming in.NET.

Properties of the Uri ClassName Description

AbsolutePath Gets the absolute path of the URI.

AbsoluteUri Gets the absolute URI.

Authority Gets the Domain Name System (DNS) host name or IP address and the port number for a server.

DnsSafeHost Gets an un-escaped host name that is safe to use for DNS resolution.

Fragment Gets the escaped fragment.

Host Gets the host component of this instance.

HostNameType Returns the type of the host name specified in the URI.

IsAbsoluteUri Gets a Boolean value that indicates whether the Uri instance is absolute.

IsDefaultPort Gets a value indicating whether the port value of the URI is the default for this scheme.

IsFile Gets a value indicating whether the specified Uri is a file URI.

IsLoopback Gets a Boolean value indicating whether the specified Uri references the local host.

IsUnc Gets a Boolean value indicating whether the specified Uri is a universal naming convention (UNC) path.

LocalPath Gets a local operating-system representation of a file name.

OriginalString Gets the original URI string that was passed to the Uri constructor.

PathAndQuery Gets the AbsolutePath and Query properties separated by a question mark (?).

Port Gets the port number of this URI.

Query Gets any query information included in the specified URI.

Scheme Gets the scheme name for this URI.

Segments Gets an array containing the path segments that make up the specified URI.

UserEscaped Indicates that the URI string was completely escaped before the Uri instance was created.

UserInfo Gets the user name, password, or other user-specific information associated with the specified URI.

Page 22: Network Programming Chapter 3: Network Programming in.NET.

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

Page 23: Network Programming Chapter 3: Network Programming in.NET.

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

Page 24: Network Programming Chapter 3: Network Programming in.NET.

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();

Page 25: 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

Page 26: Network Programming Chapter 3: Network Programming in.NET.

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)

Page 27: Network Programming Chapter 3: Network Programming in.NET.

IP Addresses

• Predefined AddressesName Description

AnyProvides an IP address that indicates that the server must listen for

client activity on all network interfaces. This field is read-only.

Broadcast Provides the IP broadcast address. This field is read-only.

IPv6AnyThe Socket.Bind method uses the IPv6Any field to indicate that a

Socket must listen for client activity on all network interfaces.

IPv6Loopback Provides the IP loopback address. This property is read-only.

IPv6NoneProvides an IP address that indicates that no network interface should

be used. This property is read-only.

Loopback Provides the IP loopback address. This field is read-only.

NoneProvides an IP address that indicates that no network interface should

be used. This field is read-only.

See IPAddressClassDemo

Page 28: Network Programming Chapter 3: Network Programming in.NET.

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

Page 29: 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

Page 30: Network Programming Chapter 3: Network Programming in.NET.

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

Page 31: Network Programming Chapter 3: Network Programming in.NET.

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

Page 32: Network Programming Chapter 3: Network Programming in.NET.

Dns Class - MethodsName Description

BeginGetHostAddressesAsynchronously returns the Internet Protocol (IP) addresses for the specified host.

BeginGetHostByNameBegins an asynchronous request for IPHostEntry information about the specified DNS host name.

BeginGetHostEntryOverloaded. Asynchronously resolves a host name or IP address to an IPHostEntry instance.

BeginResolveBegins an asynchronous request to resolve a DNS host name or IP address to an IPAddress instance.

EndGetHostAddresses Ends an asynchronous request for DNS information.

EndGetHostByName Ends an asynchronous request for DNS information.

EndGetHostEntry Ends an asynchronous request for DNS information.

EndResolve Ends an asynchronous request for DNS information.

Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetHostAddresses Returns the Internet Protocol (IP) addresses for the specified host.

Page 33: Network Programming Chapter 3: Network Programming in.NET.

Dns Class - Methods

Name Description

GetHostByAddress Static method. Overloaded. Gets DNS host information for an IP address.

GetHostByName Static method. Gets the DNS information for the specified DNS host name.

GetHostEntry Overloaded. Resolves a host name or IP address to an IPHostEntry instance.

GetHostName Gets the host name of the local computer.

GetType  Gets the Type of the current instance. (Inherited from Object.)

ReferenceEquals 

Determines whether the specified Object instances are the same instance. (Inherited from Object.)

ResolveStatic method. Obsolete in Framework 2 – use GetHostEntry. Resolves a DNS host name or IP address to an IPHostEntry instance.

ToString  Returns a String that represents the current Object. (Inherited from Object.)

Page 34: 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

Page 35: Network Programming Chapter 3: Network Programming in.NET.

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

Page 36: Network Programming Chapter 3: Network Programming in.NET.

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

Page 37: Network Programming Chapter 3: Network Programming in.NET.

How is an IP Address Resolved?

• NetBIOS node types

Node type Description Resolve name to IP address

B-node Broadcast A broadcast node.  Uses NetBIOS name queries.

H-node HybridA hybrid node. Also a

mixture of B-node and P-node (P then B)

Uses a NetBIOS name server (NBNS), for example, Windows Internet Name Service (WINS).

M-node MixedA mixed node. A mixture of

B-node and P-node (B then P)

Attempts to resolve by first using NetBIOS name queries and then using an NBNS.

P-node Peer2PeerA peer-to-peer node. Also

known as a point-to-point node

Attempts to resolve by first using an NBNS and then using a NetBIOS name query.

  Unknown An unknown node type. 

Page 38: Network Programming Chapter 3: Network Programming in.NET.

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(); }

Page 39: Network Programming Chapter 3: Network Programming in.NET.

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); } }}

Page 40: 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

Page 41: Network Programming Chapter 3: Network Programming in.NET.

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

Page 42: Network Programming Chapter 3: Network Programming in.NET.

Requests and Responsesusing 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(); } }}

Page 43: Network Programming Chapter 3: Network Programming in.NET.

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

Page 44: Network Programming Chapter 3: Network Programming in.NET.

Web Request Class Static Methods

Name Description

Create Overloaded. Initializes a new WebRequest.

CreateDefaultInitializes a new WebRequest instance for the specified URI scheme.

GetSystemWebProxyReturns a proxy configured with the Internet Explorer settings of the currently impersonated user.

ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)

RegisterPrefixRegisters a WebRequest descendant for the specified URI.

Page 45: Network Programming Chapter 3: Network Programming in.NET.

Web Request Class Instance Methods

Name Description

Abort Aborts the Request

BeginGetRequestStream When overridden in a descendant class, provides an asynchronous version of the GetRequestStream method.

BeginGetResponseWhen overridden in a descendant class, begins an asynchronous request for an Internet resource.

CreateObjRef  Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)

EndGetRequestStreamWhen overridden in a descendant class, returns a Stream for writing data to the Internet resource.

EndGetResponse When overridden in a descendant class, returns a WebResponse.

Equals  Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetHashCode  Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetLifetimeService  Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

GetRequestStreamWhen overridden in a descendant class, returns a Stream for writing data to the Internet resource.

GetResponse When overridden in a descendant class, returns a response to an Internet request.

GetType  Gets the Type of the current instance. (Inherited from Object.)

InitializeLifetimeService  Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

ToString  Returns a String that represents the current Object. (Inherited from Object.)

Page 46: Network Programming Chapter 3: Network Programming in.NET.

Web Request PropertiesName Description

AuthenticationLevel Gets or sets values indicating the level of authentication and impersonation used for this request.

CachePolicy Gets or sets the cache policy for this request.

ConnectionGroupName When overridden in a descendant class, gets or sets the name of the connection group for the request.

ContentLength When overridden in a descendant class, gets or sets the content length of the request data being sent.

ContentType When overridden in a descendant class, gets or sets the content type of the request data being sent.

CredentialsWhen overridden in a descendant class, gets or sets the network credentials used for authenticating the request with the Internet resource.

DefaultCachePolicy Gets or sets the default cache policy for this request.

DefaultWebProxy Gets or sets the global HTTP proxy.

HeadersWhen overridden in a descendant class, gets or sets the collection of header name/value pairs associated with the request.

ImpersonationLevel Gets or sets the impersonation level for the current request.

Method When overridden in a descendant class, gets or sets the protocol method to use in this request.

PreAuthenticate When overridden in a descendant class, indicates whether to pre-authenticate the request.

Proxy When overridden in a descendant class, gets or sets the network proxy to use to access this Internet resource.

RequestUri When overridden in a descendant class, gets the URI of the Internet resource associated with the request.

Timeout Gets or sets the length of time before the request times out.

UseDefaultCredentialsWhen overridden in a descendant class, gets or sets a Boolean value that controls whether DefaultCredentials are sent with requests.

Page 47: Network Programming Chapter 3: Network Programming in.NET.

Web Response MethodsName Description

Close When overridden by a descendant class, closes the response stream.

CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)

Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

GetResponseStreamWhen overridden in a descendant class, returns the data stream from the Internet resource.

GetType  Gets the Type of the current instance. (Inherited from Object.)

InitializeLifetimeService 

Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)

ToString  Returns a String that represents the current Object. (Inherited from Object.)

Page 48: Network Programming Chapter 3: Network Programming in.NET.

Web Response Properties

Name Description

ContentLengthWhen overridden in a descendant class, gets or sets the content length of data being received.

ContentTypeWhen overridden in a derived class, gets or sets the content type of the data being received.

HeadersWhen overridden in a derived class, gets a collection of header name-value pairs associated with this request.

IsFromCacheGets a Boolean value that indicates whether this response was obtained from the cache.

IsMutuallyAuthenticatedGets a Boolean value that indicates whether mutual authentication occurred.

ResponseUriWhen overridden in a derived class, gets the URI of the Internet resource that actually responded to the request.

Page 49: Network Programming Chapter 3: Network Programming in.NET.

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

Page 50: Network Programming Chapter 3: Network Programming in.NET.

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>

Page 51: Network Programming Chapter 3: Network Programming in.NET.

Requests and Responses

• Pluggable Protocols– Extend protocols by

• Adding a configuration file entry• Extending them programmatically

– New classes derived from WebRequest• E.g. FtpWebRequest for FTP protocol• Must override methods and properties of the base class to

implement protocol-specific behaviour• Create a class that implements the IWebRequestCreate

interface (E.g. FtpWebRequestCreator) and register it with the ftp scheme in the WebRequest class

Page 52: Network Programming Chapter 3: Network Programming in.NET.

Requests and Responses

• FileWebRequest and FileWebResponse– Similar to reading and writing files locally

• FileWebRequestAndFileWebResponse

Page 53: Network Programming Chapter 3: Network Programming in.NET.

Requests and Responses

• Connection Pooling– Default number of connections that can be opened to

the server at one time is defined in the configuration file machine.config

– With the default configuration we can state the number of simultaneous connections to the same host

– Can override the default number of connections• Programmatically

– ServicePoint– ServicePointManager– ConnectionGroupName

Page 54: 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

Page 55: Network Programming Chapter 3: Network Programming in.NET.

Using a Web Proxy

• Web Proxy– Proxy server routes Internet access– Reduces transfer and network connections from

Internet– Increase the performance of local clients (by caching

resources)– Caching

• Passive Caching• Active Caching

• WebProxy Class• Default Web Proxy• Changing the Web Proxy for Specific Requests

Homework: •find out what passive and active caching means•Find out how the default proxy server is set through the Internet options of your web browser

Page 56: Network Programming Chapter 3: Network Programming in.NET.

Using a Web Proxy

• WebProxy Class– Used to define a proxy server– See WebProxy Properties

• Default Web Proxy– GlobalProxySelection class (obsolete)– Use the Select property to set a different

proxy for all uses of WebRequest.GetResponse

Page 57: Network Programming Chapter 3: Network Programming in.NET.

WebProxy Class Properties

Name Description

Address Gets or sets the address of the proxy server.

BypassArrayListGets a list of addresses that do not use the proxy server.

BypassListGets or sets an array of addresses that do not use the proxy server.

BypassProxyOnLocalGets or sets a value that indicates whether to bypass the proxy server for local addresses.

CredentialsGets or sets the credentials to submit to the proxy server for authentication.

UseDefaultCredentialsGets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

Page 58: Network Programming Chapter 3: Network Programming in.NET.

Using a Web Proxy

• Changing the Web Proxy for Specific Requests– Multiple proxy servers may be utilised to distribute the

load (or security requirements)– To select a different proxy, you just have to set the Proxy property of the WebRequest class

– The Proxy property of the WebRequest class accepts an object that implements the IWebProxy interface

– WebProxy Class’s constructor is overloaded and can accept a URI to a server, and also all the parameters to configure a WebProxy object that you know already

– WebProxy Demo

Page 59: 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

Page 60: Network Programming Chapter 3: Network Programming in.NET.

Authentication• You can create user credentials and pass them to the web request• Interfaces and classes utilised:

– ICredentials– NetworkCredential– CredentialCache

• For user authentication create NetworkCredential object– Basic authentication– Digest authentication– NTLM authentication– Kerberos authentication– Does not support public key authentication (e.g. SSL)

• NetworkCredential constructor accepts– User name– Password– Domain (optional)

Page 61: Network Programming Chapter 3: Network Programming in.NET.

Authentication

• If you want to use multiple credential information for different URIs, you can use the CredentialCache class

• With this cache you can also define the authentication type for a specific connection

• To use the Windows logon credentials of the currently logged-on user, you can use the default credentials that can be accessed with CredentialCache.DefaultCredentials– Can only be used with

• NTLM• Negotiate• Kerberos

Page 62: 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

Page 63: Network Programming Chapter 3: Network Programming in.NET.

Permissions• DnsPermission

– Required to do DNS name lookups wit the Dns class• WebPermission

– Used by classes in the System.Net namespace that use URIs to send and receive data from the web

• SocketPermission– Used to accept data on a local socket or to connect to a host using a

transport protocol• Using Permission Attributes

– All applications that are installed locally on a system have full trust, so all permissions are available by default.

– .NET applications can also be started on a network share, or assemblies can be downloaded from the Internet. In these situations, many permissions are not available by default; therefore you have to configure the security settings for these applications.

• Configuring Permissions

Page 64: Network Programming Chapter 3: Network Programming in.NET.

DnsPermission

• Need DnsPermission– IP address lookup– Differentiate between allow and deny– DNS queries can be either completely

unrestricted or not allowed at all

Page 65: Network Programming Chapter 3: Network Programming in.NET.

WebPermission

• Required for classes such as WebRequest and WebResponse for sending data to and receiving data from the Internet

• Differentiates between– Accept permissions

• Needed for URIs used inside classes and methods

– Connect permissions• Needed to run client programs that connect to a server

• Lists the URIs that you can connect to • Lists the URIs that are accepted

Page 66: Network Programming Chapter 3: Network Programming in.NET.

SocketPermission

• Needed for socket classes from the System.Net namespace

• Most flexible permission of the three network permission classes

• Can pass the NetworkAccess.Accept enumerator value

• Client applications can use the NetworkAccess.Connect

• Can restrict connection to specific host and port numbers

• Can define a transport protocol

Page 67: Network Programming Chapter 3: Network Programming in.NET.

Using Permission Attributes

• SecurityException– Privileged method called without necessary

permission– Need to handle exception gracefully– Avoid by marking the assembly with the

permissions that you need (put permissions needed in square brackets above the privileged method). This means that the SecurityException happens as soon as the program is run.

Page 68: Network Programming Chapter 3: Network Programming in.NET.

Using Permission Attributes

• Permission Attribute Parameters– Enumeration

•SecurityAction• Passed through any permission attribute

– WebPermissionAttribute Class• Used to set properties

– SocketPermissionAttribute Class• Additional properties

Page 69: Network Programming Chapter 3: Network Programming in.NET.

SecurityAction Enumeration Values

Member name Description

Assert The calling code can access the resource identified by the current permission object, even if callers higher in the stack have not been granted permission to access the resource (see Using the Assert Method). 

Demand All callers higher in the call stack are required to have been granted the permission specified by the current permission object (see Security Demands). 

Deny The ability to access the resource specified by the current permission object is denied to callers, even if they have been granted permission to access it (see Using the Deny Method). 

InheritanceDemand The derived class inheriting the class or overriding a method is required to have been granted the specified permission. 

LinkDemand The immediate caller is required to have been granted the specified permission. 

For more information on declarative security and link demands, see Declarative Security Used with Class and Member Scope.

PermitOnly Only the resources specified by this permission object can be accessed, even if the code has been granted permission to access other resources (see Using the PermitOnly Method). 

RequestMinimum The request for the minimum permissions required for code to run. This action can only be used within the scope of the assembly. 

RequestOptional The request for additional permissions that are optional (not required to run). This action can only be used within the scope of the assembly. 

RequestRefuse The request that permissions that might be misused will not be granted to the calling code. This action can only be used within the scope of the assembly. 

Page 70: Network Programming Chapter 3: Network Programming in.NET.

WebPermissionAttribute Properties

Name Description

Accept Gets or sets the URI string accepted by the current WebPermissionAttribute.

AcceptPattern

Gets or sets a regular expression pattern that describes the URI accepted by the current WebPermissionAttribute.

Action  Gets or sets a security action. (Inherited from SecurityAttribute.)

Connect

Gets or sets the URI connection string controlled by the current WebPermissionAttribute.

ConnectPattern

Gets or sets a regular expression pattern that describes the URI connection controlled by the current WebPermissionAttribute.

TypeId  When implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)

Unrestricted  Gets or sets a value indicating whether full (unrestricted) permission to the resource protected by the attribute is declared. (Inherited from SecurityAttribute.)

Page 71: Network Programming Chapter 3: Network Programming in.NET.

SocketPermissionAttribute Properties

Name Description

AccessGets or sets the network access method that is allowed by this SocketPermissionAttribute.

Action  Gets or sets a security action. (Inherited from SecurityAttribute.)

Host

Gets or sets the DNS host name or IP address that is specified by this SocketPermissionAttribute.

Port

Gets or sets the port number that is associated with this SocketPermissionAttribute.

TransportGets or sets the TransportType that is specified by this SocketPermissionAttribute.

TypeId  When implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)

Unrestricted  Gets or sets a value indicating whether full (unrestricted) permission to the resource protected by the attribute is declared. (Inherited from SecurityAttribute.)

Page 72: Network Programming Chapter 3: Network Programming in.NET.

Using Permission Attributes

• Strong Name Assemblies– If you start network applications over an intranet or the Internet,

you have to assign permissions– Adds complexity if you add permissions to each application– Better to identify specific assembly or a group of assemblies and

configure permissions only for them– Strong names in .NET

• may be used to uniquely identify assemblies• Prevent tampering with assemblies• To create a strong name, use the sn utility• Use the assembly attribute AssemblyKeyFile and add a public

key and a signature to the assembly– See AssemblyKeyFileAttribute class in the System.Reflection namespace

Homework – find out how to code and assemble using strong names

Page 73: Network Programming Chapter 3: Network Programming in.NET.

AssemblyKeyFileAttributes Methods

Name Description

Equals  Overloaded. (Inherited from Attribute.)

GetCustomAttribute  Overloaded. Retrieves a custom attribute of a specified type applied to an assembly, module, type member, or method parameter. (Inherited from Attribute.)

GetCustomAttributes 

Overloaded. Retrieves an array of the custom attributes applied to an assembly, module, type member, or method parameter. (Inherited from Attribute.)

GetHashCode  Returns the hash code for this instance. (Inherited from Attribute.)

GetType  Gets the Type of the current instance. (Inherited from Object.)

IsDefaultAttribute  When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)

IsDefined  Overloaded. Determines whether any custom attributes of a specified type are applied to an assembly, module, type member, or method parameter. (Inherited from Attribute.)

Match  When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)

ReferenceEquals  Determines whether the specified Object instances are the same instance. (Inherited from Object.)

ToString  Returns a String that represents the current Object. (Inherited from Object.)

Page 74: Network Programming Chapter 3: Network Programming in.NET.

Configuring Permissions• Applications installed locally

– Have full trust by default– No need to configure these applications

• Starting applications from an intranet– Have Dns permissions by default– Need to configure the WebPermission and SocketPermission explicitly

• To configure permissions– Need

• Command-line utility caspol.exe• .NET Framework configuration tool Windows application (Control Panel)

– Steps• Create a new permission set (if necessary)• Configure the necessary permissions (e.g. DNS, Web Access) using the wizard• Need to add User Interface permission (for Windows applications)• You may use URIs to restrict permissions• Create a new code group (if necessary)• Condition types can be specified to define the assemblies that belong to each code

group• The condition can be an application directory, URI, or a site

Page 75: Network Programming Chapter 3: Network Programming in.NET.

Homework

• Check how to configure permissions for a group of assemblies

Page 76: 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