Module 11: Internet Access |
19 |
|
|
|
Internet Domain Name System
Topic Objective
To explain how to use the Dns class to retrieve information about a host.
Lead-in
The Dns class is a static class that retrieves information about a specific host from the Internet Domain Name System.
!Dns Class Retrieves Data About a Host from DNS
"GetHostByName query for www.contoso.com
IPHostEntry hostInfo =
IPHostEntry hostInfo =
Dns.GetHostByName("www.contoso.com");
Dns.GetHostByName("www.contoso.com");
" Resolve query for www.contoso.com
IPHostEntry hostInfo =
IPHostEntry hostInfo =
Dns.Resolve("www.contoso.com");
Dns.Resolve("www.contoso.com");
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The Dns class is a static class that retrieves information about a specific host from the Internet Domain Name System (DNS).
The host information from a GetHostByName query is returned in an instance of the IPHostEntry class. If the specified host has more than one entry in the DNS database, IPHostEntry contains multiple Internet Protocol (IP) addresses and aliases.
The following example queries the DNS database for information about a host that is called www.contoso.com:
IPHostEntry hostInfo = Dns.GetHostByName("www.contoso.com");
The Resolve method queries a DNS server for the IP address that is associated with a host name, such as www.contoso.com, or for an IP address in dotted-quad notation, such as 192.168.1.2.
When the host name is a DNS-style host name that is associated with multiple IP addresses, only the first IP address that resolves to that host name is returned, as in the following example:
IPHostEntry hostInfo = Dns.Resolve("www.contoso.com");
20 |
Module 11: Internet Access |
Topic Objective
To explain how to use the
TcpClient and TcpListener classes to request data from an Internet resource and to monitor TCP ports.
Lead-in
Applications can use TCP and UDP services with the
TcpClient, TcpListener, and UdpClient classes.
! TCP Client Connecting to a Server/Listener
TcpClient tcpc = new TcpClient(serverURI, 14); TcpClient tcpc = new TcpClient(serverURI, 14); Stream s = tcpc.GetStream();
Stream s = tcpc.GetStream();
Byte[] read = new Byte[32];
Byte[] read = new Byte[32];
int bytes = s.Read(read, 0, read.Length); int bytes = s.Read(read, 0, read.Length);
String strInData = Encoding.ASCII.GetString(read); String strInData = Encoding.ASCII.GetString(read);
! TCP Server/Listener Monitors Port for Clients
TcpListener tcpl = new TcpListener(14); |
TcpListener tcpl = new TcpListener(14); |
tcpl.Start(); |
|
tcpl.Start(); |
{ |
while (!done) |
while (!done) |
{ |
// Accept will block until someone connects // Accept will block until someone connects Socket s = tcpl.AcceptSocket();
Socket s = tcpl.AcceptSocket(); //Code to handle request goes here
}} //Code to handle request goes here
tcpl.Stop();
tcpl.Stop();
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Applications can use TCP and UDP services with the TcpClient, TcpListener, and UdpClient classes. These classes, which are built on top of the Socket class, represent the data that is sent and received from the network as streams. These classes also take care of the details of creating a connection.
Using the TcpClient Class
You use the TcpClient class to request data from an Internet resource that uses TCP. The methods and properties of TcpClient abstract the details for creating a Socket instance that requests and receives data through TCP. The connection to the Internet is represented as a stream; therefore data can be read and written in a standard manner.
The following code demonstrates how to set up a TcpClient object to connect to a server on TCP port 14:
TcpClient tcpc = new TcpClient(serverURI, 14); Stream s = tcpc.GetStream();
Byte[] read = new Byte[32];
int bytes = s.Read(read, 0, read.Length);
String strInData = Encoding.ASCII.GetString(read);
Module 11: Internet Access |
21 |
|
|
|
Using the TcpListener Class
You use a TcpListener object to monitor a TCP port for incoming requests and then create a Socket instance that manages the connection to the client. The Start method enables listening, and the Stop method disables listening on the port. The AcceptSocket method accepts incoming connection requests and creates the socket that will handle the request.
The following code demonstrates how to set up a TcpListener object to monitor TCP port 14:
TcpListener tcpl = new TcpListener(14); // listen on port 14
tcpl.Start(); |
|
while (!done) |
{ |
// Accept will block until someone connects Socket s = tcpl.AcceptSocket();
//Code to handle request goes here
}
tcpl.Stop();
22 |
Module 11: Internet Access |
Sockets
Topic Objective
To describe the Socket class and provide an example of how the Socket class can be used to send data to an HTTP server and to receive the response.
Lead-in
The System.Net.Sockets namespace contains an implementation of the
Windows Sockets interface.
!System.Net Classes Are Built on System.Net.Sockets
!System.Net.Sockets Are Based on the WinSock32 API
!See Example in Student Notes
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The System.Net.Sockets namespace contains an implementation of the
Windows Sockets interface. All other network access classes in the
System.Net namespace are built on top of this implementation of sockets.
The .NET Framework’s Socket class is a managed code version of the socket services that are provided by the WinSock32 API. If you are familiar with the Winsock API, you should be comfortable using the Socket class to develop applications. In most cases, the Socket class methods simply marshal data into their native Microsoft Win32® counterparts and handle necessary security checks.
Module 11: Internet Access |
23 |
|
|
|
The following example shows how the Socket class can be used to send data to an HTTP server and receive the response:
using System; using System.Net;
using System.Net.Sockets; using System.IO;
using System.Text;
class App
{
public static void Main(string[] args)
{
DoSocketGet("localhost");
}
public static string DoSocketGet(string server)
{
//Set up variables and String to write to the server Encoding ASCII = Encoding.ASCII;
string Get = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n";
Byte[] ByteGet = ASCII.GetBytes(Get); Byte[] RecvBytes = new Byte[256]; String strRetPage = "";
//IPHostEntry and IPEndPoint
//represent the endpoint that
//will receive the request
IPHostEntry hostEntry = Dns.Resolve(server);
IPEndPoint EPhost = new
IPEndPoint(hostEntry.AddressList[0], 80);
//Create the Socket for sending data over TCP
Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
// Connect to host using IPEndPoint try
{
mySocket.Connect(EPhost);
//Sent the GET text to the host mySocket.Send(ByteGet, ByteGet.Length, 0);
//Receive the page, loop until all received Int32 bytes = mySocket.Receive(RecvBytes,
RecvBytes.Length, 0);
strRetPage = "Default HTML page on " + server +
":\r\n";
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
(Code continued on the following page.)
24 |
Module 11: Internet Access |
while (bytes > 0)
{
bytes = mySocket.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
}
}
catch (Exception e)
{
Console.WriteLine("Exception {0}",e.ToString());
}
return strRetPage;
}
}
Module 11: Internet Access |
25 |
|
|
|
Handling Errors
Topic Objective
To explain how the Status property is used to determine if an error has occurred.
Lead-in
The WebRequest and WebResponse classes throw system exceptions and Web-specific exceptions, which are instances of WebException and thrown by the
GetResponse method.
!A WebException Can Be Thrown by GetResponse
"Has Status property, value from WebExceptionStatus
"If WebExceptionStatus.ProtocolError, then WebResponse contains protocol error information
try |
|
|
{try |
// ... Create a request, get response and process stream. } |
{ // ... Create a request, get response and process stream. } |
catch (WebException webExcp) |
|
catch (WebException webExcp) |
|
{{ |
Console.WriteLine("A WebException has been caught"); |
|
Console.WriteLine("A WebException has been caught"); |
|
Console.WriteLine(webExcp.ToString()); |
|
Console.WriteLine(webExcp.ToString()); |
|
WebExceptionStatus status = |
webExcp.Status; |
|
WebExceptionStatus status = |
webExcp.Status; |
|
if (status == WebExceptionStatus.ProtocolError) { |
|
if (status == WebExceptionStatus.ProtocolError) { |
Console.Write(
Console.Write(
}}
}}
"The server returned protocol error "); "The server returned protocol error "); Console.WriteLine(webExcp.Response.ToString()); Console.WriteLine(webExcp.Response.ToString());
catch (Exception e) catch (Exception e)
{// Code to catch other exceptions goes here.} {// Code to catch other exceptions goes here.}
*****************************ILLEGAL FOR NON-TRAINER USE******************************
The WebRequest and WebResponse classes throw system exceptions, such as InvalidArgumentException, and Web-specific exceptions, which are instances of WebException and are thrown by the GetResponse method.
Each WebException includes a Status property that contains a value from the WebExceptionStatus class. You can examine the Status property to determine the particular error that has occurred and take the proper steps to resolve the error.
The following table describes some of the possible values for the Status property. For a complete list of values, see the .NET Framework SDK documentation.
Value |
Description |
|
|
ConnectFailure |
The remote service could not be contacted at the |
|
transport level. |
ConnectionClosed |
The connection was closed prematurely. |
KeepAliveFailure |
The server closed a connection made with the Keep-alive |
|
header set. |
NameResolutionFailure |
The name service could not resolve the host name. |
ProtocolError |
The response received from the server was complete but |
|
indicated an error at the protocol level. |
ReceiveFailure |
A complete response was not received from the remote |
|
server. |
RequestCanceled |
The request was canceled. |
SecureChannelFailure |
An error occurred in a secure channel link. |
SendFailure |
A complete request could not be sent to the remote |
|
server. |
26 |
Module 11: Internet Access |
(continued) |
|
Value |
Description |
|
|
ServerProtocolViolation |
The server response was not a valid HTTP response. |
Success |
No error was encountered. |
Timeout |
No response was received within the time-out set for the |
|
request. |
TrustFailure |
A server certificate could not be validated. |
When the Status property is WebExceptionStatus.ProtocolError, a
WebResponse that contains the response from the server is available. You can examine this response to determine the actual source of the protocol error.
The following example shows how to catch a WebException; the invalid URL argument in the WebRequest.Create call will throw an exception:
using System; using System.Net; using System.IO; using System.Text;
class App
{
public static void Main(string[] args)
{
try
{
//Create a request instance
//Note invalid URL will throw exception WebRequest myRequest =
WebRequest.Create("http://localhost_bad_URL");
//Get the response.
WebResponse myResponse = myRequest.GetResponse();
//Get a readable stream from the server. StreamReader sr = new StreamReader(
myResponse.GetResponseStream(), Encoding.ASCII);
int length = 1024;
char [] Buffer = new char[1024]; int bytesread = 0;
//Read from the stream and write data to Console. bytesread = sr.Read( Buffer, 0, length);
while( bytesread > 0 )
{
Console.Write( Buffer, 0, bytesread); bytesread = sr.Read( Buffer, 0, length);
}
sr.Close();
myResponse.Close();
}
(Code continued on the following page.)
Module 11: Internet Access |
27 |
|
|
|
catch (WebException webExcp)
{
Console.WriteLine("A WebException has been caught");
//Write out the WebException message. Console.WriteLine(webExcp.ToString());
//Get the WebException status code. WebExceptionStatus status = webExcp.Status;
//If status is WebExceptionStatus.ProtocolError,
//there has been a protocol error and a
//WebResponse should exist.
//Display the protocol error.
if (status == WebExceptionStatus.ProtocolError)
{
Console.Write(
"The server returned protocol error "); Console.WriteLine(webExcp.Response.ToString());
}
}
catch (Exception e)
{
// Code to catch other exceptions goes here.
}
}
}
Applications that use the Socket class throw instances of SocketException when errors occur on the Windows socket. The TcpClient, TcpListener, and UdpClient classes are built on top of the Socket class and also throw instances of SocketException.
When a SocketException is thrown, the Socket class sets the ErrorCode property to the last operating system socket error that occurred.
28 |
Module 11: Internet Access |
# Security
Topic Objective
To introduce the topics in the section.
Lead-in
Your application can provide security for sending and receiving data over the Internet by using a Web proxy, SSL encryption, Internet authentication, and the NET Framework’s code access permissions.
!Web Proxy
!Secure Sockets Layer
!Internet Authentication
!Permissions
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Your application can provide security for sending and receiving data over the
Internet by using a Web proxy, Secure Sockets Layer (SSL) encryption,
Internet authentication, and the NET Framework’s code access permissions.