Presentation is loading. Please wait.

Presentation is loading. Please wait.

Network Programming Chapter 3: Network Programming in.NET.

Similar presentations


Presentation on theme: "Network Programming Chapter 3: Network Programming in.NET."— Presentation transcript:

1 Network Programming Chapter 3: Network Programming in.NET

2 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions

3 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

4 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

5 System.Net Classes Authentication and Authorization –AuthenticationManager class has static methods to authenticate the client user «utility» AuthenticationManager «interface» IAuthenticationModule Authorization AuthenticationModule «interface» ICredentials CredentialCacheNetworkCredential Returns Caches

6 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

7 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 ServicePoint manages

8 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

9 System.Net Classes Cookies HttpWebRequest CookieContainer CookieCollection CookieContainer HttpWebResponse Cookies Cookie

10 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

11 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

12 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions

13 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

14 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:Internet standardSTD 66RFC 3986 : [ ? ] [ # ] –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.domain nameIP addressport numberdirectories –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 = 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.

15 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

16 Working with URIs Reserved URI characters ; / ? : @ & = + $, URI Class –In the System namespace –Has properties and methods for parsing, comparing and combining URIs

17 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.as p);http://msdn.microsoft.com/code/default.as p Create a new Uri object by combining a known base Uri with a relative URI Uri baseUri = new Uri(http://msdn.microsoft.com);http://msdn.microsoft.com Uri newUri = new Uri(baseUri, “code/default.asp”); –Commonly Used Schemes –Checking for a Valid Host Name and Scheme

18 Working with URIs Uri Class –Commonly Used Schemes NameDescription UriSchemeFile Specifies that the URI is a pointer to a file. This field is read-only. UriSchemeFtp Specifies 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. UriSchemeHttp Specifies that the URI is accessed through the Hypertext Transfer Protocol (HTTP). This field is read-only. UriSchemeHttps Specifies that the URI is accessed through the Secure Hypertext Transfer Protocol (HTTPS). This field is read-only. UriSchemeMailto Specifies that the URI is an e-mail address and is accessed through the Simple Mail Transport Protocol (SMTP). This field is read-only. UriSchemeNetPipe Specifies that the URI is accessed through the NetPipe scheme of the "Indigo" system. This field is read-only. UriSchemeNetTcp Specifies that the URI is accessed through the NetTcp scheme of the "Indigo" system. This field is read-only. UriSchemeNews Specifies that the URI is an Internet news group and is accessed through the Network News Transport Protocol (NNTP). This field is read-only. UriSchemeNntp Specifies that the URI is an Internet news group and is accessed through the Network News Transport Protocol (NNTP). This field is read-only.

19 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)

20 Working with URIs UriHostNameType enumeration Member nameDescription BasicThe host is set, but the type cannot be determined. DnsThe host name is a domain name system (DNS) style host name. IPv4The host name is an Internet Protocol (IP) version 4 host address. IPv6The host name is an Internet Protocol (IP) version 6 host address. UnknownThe type of the host name is not supplied.

21 Properties of the Uri Class NameDescription 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. IsAbsoluteUriGets 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.

22 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

23 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

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

25 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions

26 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)

27 IP Addresses Predefined Addresses NameDescription Any Provides 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. IPv6Any The 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. IPv6None Provides 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. None Provides an IP address that indicates that no network interface should be used. This field is read-only. See IPAddressClassDemo

28 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

29 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions

30 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

31 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

32 Dns Class - Methods NameDescription BeginGetHostAddresses Asynchronously returns the Internet Protocol (IP) addresses for the specified host. BeginGetHostByName Begins an asynchronous request for IPHostEntry information about the specified DNS host name. BeginGetHostEntry Overloaded. Asynchronously resolves a host name or IP address to an IPHostEntry instance. BeginResolve Begins 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.

33 Dns Class - Methods NameDescription 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.) Resolve Static 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.)

34 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions

35 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. \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

36 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

37 How is an IP Address Resolved? NetBIOS node types Node typeDescriptionResolve name to IP address B-node BroadcastA broadcast node. Uses NetBIOS name queries. H-nodeHybrid A 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-nodeMixed A 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-nodePeer2Peer A 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. UnknownAn unknown node type.

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

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

40 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions

41 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

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

43 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

44 Web Request Class Static Methods NameDescription CreateOverloaded. Initializes a new WebRequest. CreateDefault Initializes a new WebRequest instance for the specified URI scheme. GetSystemWebProxy Returns 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.) RegisterPrefix Registers a WebRequest descendant for the specified URI.

45 Web Request Class Instance Methods NameDescription Abort Aborts the Request BeginGetRequestStreamWhen overridden in a descendant class, provides an asynchronous version of the GetRequestStream method. BeginGetResponse When 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.) EndGetRequestStream When overridden in a descendant class, returns a Stream for writing data to the Internet resource. EndGetResponseWhen 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.) GetRequestStream When 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.)

46 Web Request Properties NameDescription 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. Credentials When 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. Headers When 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. UseDefaultCredentials When overridden in a descendant class, gets or sets a Boolean value that controls whether DefaultCredentials are sent with requests.

47 Web Response Methods NameDescription 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.) GetResponseStream When overridden in a descendant class, returns the data stream from the Internet resource. GetType Gets the Type of the current instance. (Inherited from Object.) InitializeLifetimeSer vice 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.)

48 Web Response Properties NameDescription ContentLength When overridden in a descendant class, gets or sets the content length of data being received. ContentType When overridden in a derived class, gets or sets the content type of the data being received. Headers When overridden in a derived class, gets a collection of header name-value pairs associated with this request. IsFromCache Gets a Boolean value that indicates whether this response was obtained from the cache. IsMutuallyAuthenticated Gets a Boolean value that indicates whether mutual authentication occurred. ResponseUri When overridden in a derived class, gets the URI of the Internet resource that actually responded to the request.

49 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

50 Pluggable Protocols http, https & file schemes are pre-defined in the machine.config file \Microsoft.NET\Framework\ \CONFIG

51 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

52 Requests and Responses FileWebRequest and FileWebResponse –Similar to reading and writing files locally FileWebRequestAndFileWebResponse

53 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

54 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions

55 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

56 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

57 WebProxy Class Properties NameDescription AddressGets or sets the address of the proxy server. BypassArrayList Gets a list of addresses that do not use the proxy server. BypassList Gets or sets an array of addresses that do not use the proxy server. BypassProxyOnLocal Gets or sets a value that indicates whether to bypass the proxy server for local addresses. Credentials Gets or sets the credentials to submit to the proxy server for authentication. UseDefaultCredentials Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

58 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

59 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions

60 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)

61 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

62 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions

63 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

64 DnsPermission Need DnsPermission –IP address lookup –Differentiate between allow and deny –DNS queries can be either completely unrestricted or not allowed at all

65 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

66 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

67 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.

68 Using Permission Attributes Permission Attribute Parameters –Enumeration SecurityAction Passed through any permission attribute –WebPermissionAttribute Class Used to set properties –SocketPermissionAttribute Class Additional properties

69 SecurityAction Enumeration Values Member nameDescription AssertThe 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). DemandAll callers higher in the call stack are required to have been granted the permission specified by the current permission object (see Security Demands). DenyThe 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). InheritanceDemandThe derived class inheriting the class or overriding a method is required to have been granted the specified permission. LinkDemandThe 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. PermitOnlyOnly 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). RequestMinimumThe request for the minimum permissions required for code to run. This action can only be used within the scope of the assembly. RequestOptionalThe request for additional permissions that are optional (not required to run). This action can only be used within the scope of the assembly. RequestRefuseThe 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.

70 WebPermissionAttribute Properties NameDescription AcceptGets 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.)

71 SocketPermissionAttribute Properties NameDescription Access Gets 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. Transport Gets 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.)

72 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

73 AssemblyKeyFileAttributes Methods NameDescription 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.)

74 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

75 Homework Check how to configure permissions for a group of assemblies

76 Topics System.Net Classes Overview Working with URIs IP Addresses Dns Class Requests and Responses Using a Web Proxy Authentication Permissions


Download ppt "Network Programming Chapter 3: Network Programming in.NET."

Similar presentations


Ads by Google