Network Programming

Download Report

Transcript Network Programming

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
«utility»
AuthenticationManager
Returns
Authorization
«interface»
IAuthenticationModule
«interface»
ICredentials
AuthenticationModule
Returns
CredentialCache
Caches
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
HttpWebRequest
FileWebRequest
HttpWebResponse
FileWebResponse
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
HttpWebRequest
CookieContainer
CookieContainer
HttpWebResponse
Cookies
CookieCollection
Cookie
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 connectionorientated 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 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.
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
scheme Authority (server & port)
path
urn:example:animal:ferret:nose
query
fragment
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.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);
• 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
Name
Description
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.
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
UriHostNameType enumeration
Member 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.
Properties of the Uri Class
Name
Description
AbsolutePath
Gets the absolute path of the URI.
AbsoluteUri
Gets the absolute URI.
Gets the Domain Name System (DNS) host name or IP address and the port number for a server.
Authority
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.
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
Name
Description
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
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
Dns Class - Methods
Name
Description
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.
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.)
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.)
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
Node type
Description
Resolve name to IP address
Broadcast
A broadcast node.
Uses NetBIOS name queries.
Hybrid
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-node
Mixed
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-node
Peer2Peer
A peer-to-peer node. Also
known as a point-topoint node
Attempts to resolve by first using an NBNS and then
using a NetBIOS name query.
Unknown
An unknown node type.
B-node
H-node
Resolving the IP Address
Asynchronously
using
using
using
using
System;
System.Collections.Generic;
System.Text;
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
using
using
using
using
System;
System.Collections.Generic;
System.Text;
System.Net;
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
Web Request Class Static Methods
Name
Description
Create
Overloaded. 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.
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.
BeginGetResponse
CreateObjRef
EndGetRequestStream
When overridden in a descendant class, begins an asynchronous request for an Internet resource.
Creates an object that contains all the relevant information required to generate a proxy used to
communicate with a remote object. (Inherited from MarshalByRefObject.)
When 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.)
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.)
Web Request Properties
Name
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.
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.
Web Response Methods
Name
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.)
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.)
Web Response Properties
Name
Description
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.
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>
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
Requests and Responses
• FileWebRequest and
FileWebResponse
– Similar to reading and writing files locally
• FileWebRequestAndFileWebResponse
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
Topics
• System.Net Classes Overview
• Working with URIs
• IP Addresses
• Dns Class
• Requests and Responses
• Using a Web Proxy
• Authentication
• Permissions
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)
Homework:
– Caching
•find out what passive and active caching
• Passive Caching
• Active Caching
means
•Find out how the default proxy server is set
through the Internet options of your web
browser
• WebProxy Class
• Default Web Proxy
• Changing the Web Proxy for Specific Requests
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
WebProxy Class Properties
Name
Description
Address
Gets 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.
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
Topics
• System.Net Classes Overview
• Working with URIs
• IP Addresses
• Dns Class
• Requests and Responses
• Using a Web Proxy
• Authentication
• Permissions
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)
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
Topics
• System.Net Classes Overview
• Working with URIs
• IP Addresses
• Dns Class
• Requests and Responses
• Using a Web Proxy
• Authentication
• Permissions
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
DnsPermission
• Need DnsPermission
– IP address lookup
– Differentiate between allow and deny
– DNS queries can be either completely
unrestricted or not allowed at all
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
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
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.
Using Permission Attributes
• Permission Attribute Parameters
– Enumeration
• SecurityAction
• Passed through any permission attribute
– WebPermissionAttribute Class
• Used to set properties
– SocketPermissionAttribute Class
• Additional properties
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.
WebPermissionAttribute
Properties
Name
Description
Accept
Gets or sets the URI string accepted by the current WebPermissionAttribute.
AcceptPattern
Action
Connect
ConnectPattern
Gets or sets a regular expression pattern that describes the URI
accepted by the current WebPermissionAttribute.
Gets or sets a security action. (Inherited from SecurityAttribute.)
Gets or sets the URI connection string controlled by the current
WebPermissionAttribute.
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.)
SocketPermissionAttribute
Properties
Name
Description
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
Port
Transport
Gets or sets the DNS host name or IP address that is specified by
this SocketPermissionAttribute.
Gets or sets the port number that is associated with this
SocketPermissionAttribute.
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.)
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
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.)
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
Homework
• Check how to configure permissions for a
group of assemblies
Topics
• System.Net Classes Overview
• Working with URIs
• IP Addresses
• Dns Class
• Requests and Responses
• Using a Web Proxy
• Authentication
• Permissions