Network Programming - PowerPoint PPT Presentation

1 / 81
About This Presentation
Title:

Network Programming

Description:

A socket is one end of a two-way communication link between two programs running ... Large overhead makes it bulky for small amounts of data ... – PowerPoint PPT presentation

Number of Views:69
Avg rating:3.0/5.0
Slides: 82
Provided by: Yvo58
Category:

less

Transcript and Presenter's Notes

Title: Network Programming


1
Network Programming
  • Chapter 4
  • Socket Programming in .NET

2
Basic Outline
  • An Overview of Sockets
  • Working with Sockets in .NET
  • Asynchronous Programming
  • Socket Permissions

3
Basic Outline
  • An Overview of Sockets
  • Working with Sockets in .NET
  • Asynchronous Programming
  • Socket Permissions

4
An Overview of Sockets
  • Definition
  • A socket is one end of a two-way communication
    link between two programs running on a network
  • Connection can be local or remote
  • Socket implementation provides the encapsulation
    of the network and transport level protocols
  • A socket, being a resource, is also represented
    by a descriptor
  • Socket Types
  • Stream Sockets
  • Connection-orientated
  • Consists of a stream of bytes that can be
    bidirectional
  • Guarantees error correction, handles delivery and
    preserves data sequence and guarantees
    non-duplicated data
  • High level of quality using TCP
  • Suitable for large amounts of data
  • Large overhead makes it bulky for small amounts
    of data
  • Path is formed before communication starts
    (ensures that both parties are active and
    participating)
  • Uses data packets and relies on TCP for delivery
    of packets
  • Datagram Sockets
  • Raw Sockets
  • Sockets and Ports

5
An Overview of Sockets
  • Definition
  • Socket Types
  • Stream Sockets
  • Datagram Sockets
  • Also called connectionless sockets (no explicit
    connections are established)
  • Message is just sent without knowledge of the
    receiver
  • Uses UDP to pass data from client to server
  • Message size limitations and no guarantee of
    delivery
  • Used when overhead of stream sockets does not
    warrant the message (i.e. when the message is too
    small/insignificant)
  • Raw Sockets
  • Sockets and Ports

6
An Overview of Sockets
  • Definition
  • Socket Types
  • Stream Sockets
  • Datagram Sockets
  • Raw Sockets
  • A socket that takes packets, bypassing the TCP
    and UDP layers in the TCP/IP stack and sends them
    directly to the application
  • Purpose is to bypass the mechanism by which the
    computer handles TCP/IP.
  • Provides a custom implementation of the TCP/IP
    stack
  • It is more efficient than going through the
    clients main stack
  • No processing on the packet (i.e. raw)
  • The receiving application has to handle the data
    appropriately and deal with actions such as
    stripping off headers and parsing
  • Used for custom low-level protocol applications
  • Sockets and Ports

7
An Overview of Sockets
  • Definition
  • Socket Types
  • Stream Sockets
  • Datagram Sockets
  • Raw Sockets
  • Sockets and Ports
  • A port is defined to solve the problem of
    communicating with multiple applications
    simultaneously it basically expands the notion
    of an IP address
  • A computer can identify an arriving packet by the
    port number it is arriving through
  • Port numbers are established when connections are
    made
  • The socket is composed of the IP address of the
    machine and the port number used by the TCP
    application this is also called an endpoint.
  • Endpoints are unique across the entire Internet
    because IP addresses are unique
  • Certain services have port numbers reserved for
    them these are the well-known port numbers (FTP
    21)

8
An Overview of Sockets
Port
Server
Client
Connection Request
Normally a client/server application using
sockets consists of two different applications a
client that initiates the connection with the
target (server) and the server, which waits for
the connection from the client. For example, on
the client side, the client must know the
targets address and the port number. To make
the connection request, the client tries to
establish the connection with the server.
If everything goes well, provided that the server
is running before the client tries to connect to
it, the server accepts the connection. Upon
acceptance, the server application create a new
socket to deal specifically with the connect
client. The client and the server can now
communicate with each other by reading from and
writing to their respective sockets.
Port
Server
Port
Port
Client
Startcommunication
9
Basic Outline
  • An Overview of Sockets
  • Working with Sockets in .NET
  • Asynchronous Programming
  • Socket Permissions

10
Classes in the System.Net.Sockets Namespace
11
System.Net.Sockets.Socket Properties
12
System.Net.Sockets.Socket Properties
13
System.Net.Sockets.Socket Methods
14
System.Net.Sockets.Socket Methods
15
Working with Sockets in .NET
  • Creating a TCP Stream Socket Application
  • Building a TCP Server
  • Building a TCP Client
  • Managing Exceptions with System.NET Sockets
  • Setting and Retrieving Socket Options

16
Building a TC-based Server
Server
Open a Socket (Socket)
Name the Socket (Bind)
Listen for incoming Connection (Listen)
Accept client connection (Accept)
Send/Receive Data (Send/Receive)
Close Socket (Close)
17
  • using System
  • using System.Collections.Generic
  • using System.Text
  • using System.Net.Sockets
  • using System.Net
  • namespace TestSockets
  • class SocketServer
  • static void Main(string args)
  • //establish the local endpoint for
    the socket
  • IPHostEntry ipHost
    Dns.GetHostEntry("localhost")
  • IPAddress ipAddr ipHost.AddressList
    0
  • IPEndPoint ipEndPoint new
    IPEndPoint(ipAddr, 1100)

Note System.Net System.Net.Sockets
Returns all network addresses supported
Establish the local endpoint for the
socket. Before opening a socket, you need to
establish a local endpoint address. The local
endpoint address is the host IP Address and the
port number that is going to be used
18
  • //Create a TCP/IP Socket
  • Socket sListener new
    Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp)
  • //Bind the Socket to the local
    endpoint and listen to the incoming sockets
  • try
  • sListener.Bind(ipEndPoint)
  • sListener.Listen(10)
  • while (true)
  • Console.WriteLine("Waiting
    for connection on port 0.", ipEndPoint)

The Bind method associates a socket with a local
endpoint. You must call Bind before any attempt
to call Listen or Accept.
The maximum pending connections
19
  • //program is suspended while
    waiting for an incoming connection
  • Socket handler
    sListener.Accept()
  • string data null
  • //We got the client
    attempting to connect
  • while (true)
  • byte bytes new
    byte1024
  • int bytesRec
    handler.Receive(bytes)
  • data
    Encoding.ASCII.GetString(bytes, 0, bytesRec)
  • if (data.IndexOf("ltTheEndgt
    ") gt -1)
  • break
  • //end of while

Accept extracts the first connection in the
queue, receives the client connection and creates
a new socket to handle it. The Accept method
blocks the caller thread until the connection is
present.
Accept may open up multiple sockets. Once the
client and server are connected with each other,
you an send and receive using the Send and
Receive methods of the Socket class. The exact
protocol definition between the client and server
needs to be clearly defined before sockets may
send and receive.
20
  • //show the data on the console
  • Console.WriteLine("Text
    Received 0", data)
  • string theReply "Thank you
    for those " data.Length.ToString() "
    characters..."
  • byte msg
    Encoding.ASCII.GetBytes(theReply)
  • handler.Send(msg)
  • handler.Shutdown(SocketShutdown.Both)
  • handler.Close()
  • //end of while
  • Console.WriteLine("press a key")
  • //end of try
  • catch(Exception e)
  • Console.WriteLine(e.ToString())
  • finally
  • sListener.Close()
  • Console.ReadLine()

21
Working with Sockets in .NET
  • Creating a TCP Stream Socket Application
  • Building a TCP Server
  • Building a TCP Client
  • Managing Exceptions with System.NET Sockets
  • Setting and Retrieving Socket Options

22
Building a TC-based Client
Client
Open a Socket (Socket)
Connect to Remote Host (Connect)
Send/Receive Data (Send/Receive)
Close Socket (Close)
23
  • using System
  • using System.Collections.Generic
  • using System.Text
  • using System.Net.Sockets
  • using System.Net
  • namespace TestSocketClient
  • class SocketClient
  • static void Main(string args)
  • //Data buffer for incoming data
  • byte bytes new byte1024
  • //Connect to a remote device
  • try
  • //Establish the remote endpoint
    for the socket

24
  • Console.WriteLine("Socket
    connected to 0", sender.RemoteEndPoint.ToString(
    ))
  • string theMessage "This is a
    test."
  • byte msg Encoding.ASCII.GetByt
    es(theMessage "ltTheEndgt")
  • //Send the data through the
    socket
  • int bytesSent sender.Send(msg)
  • //Recieve the response from the
    remote device
  • int bytesRec sender.Receive(byte
    s)
  • Console.WriteLine("The Server
    says 0", Encoding.ASCII.GetString(bytes, 0,
    bytesRec))
  • //Release the Socket
  • sender.Shutdown(SocketShutdown.Bot
    h)
  • sender.Close()
  • //end of try
  • catch (Exception e)

25
Constructing a Port Scanner
  • Scans for open ports (sees who is listening)
  • Makes a connection with each port specified in
    the loop
  • Socket Exceptions have an integer value
    associated with it

26
  • using System
  • using System.Collections.Generic
  • using System.Text
  • using System.Net.Sockets
  • using System.Net
  • namespace PortScanner
  • class Program
  • static void Main(string args)
  • IPAddress address
    IPAddress.Parse("127.0.0.1")
  • int listeningPorts new int50
  • int count -1
  • Socket sSocket new
    Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp)
  • //Loop through ports 1 to 1024

27
  • //Connect the socket to the remote endpoint
  • sSocket.Connect(endPoint)
  • Console.WriteLine("Port 0
    is listening.", i.ToString())
  • count
  • listeningPortscount i
  • //end of try
  • catch (SocketException ignored)
  • if (ignored.ErrorCode !
    10061)
  • Console.WriteLine(ignored.
    Message)
  • //end of catch
  • finally
  • if (sSocket.Connected)
  • sSocket.Shutdown(SocketShu
    tdown.Both)
  • sSocket.Close()

28
Working with Sockets in .NET
  • Creating a TCP Stream Socket Application
  • Building a TCP Server
  • Building a TCP Client
  • Managing Exceptions with System.NET Sockets
  • Setting and Retrieving Socket Options

29
Managing Exceptions with System.Net.Sockets
  • Socket class generally throws the SocketException
  • SocketException thrown when
  • Mismatch or incompatibility in AddressFamily,
    SocketType or ProtocolType
  • Possible places construct new socket or connect
    method

30
Socket Exception Enumerations
31
Socket Exception Enumerations
32
Socket Exception Enumerations
33
Socket Exception Enumerations
34
Working with Sockets in .NET
  • Creating a TCP Stream Socket Application
  • Building a TCP Server
  • Building a TCP Client
  • Managing Exceptions with System.NET Sockets
  • Setting and Retrieving Socket Options

35
Setting and Retrieving Socket Options
  • SetSocketOption
  • Customise socket
  • SocketOptionLevel
  • SocketOptionName
  • Value to set for the socket option
  • GetSocketOption

36
SetSocketOption
37
Socket Option Levels
  • Enumeration
  • Used to specify at which level of the OSI model
    the option is applied

38
SocketOptionLevel
39
Socket Option Names
  • Defines the name of the parameter whose value is
    being set
  • Examples
  • ReuseAddress
  • Linger

40
SocketOptionName
41
SocketOptionName
42
SocketOptionName
43
SocketOptionName
44
ReuseAddress
  • By default only one socket may be bound to a
    local address that is already in use. However,
    you may want to bind more than one socket to a
    local address
  • The solution is the ReuseAddress

45
ReuseAddress (throws error)
  • using System
  • using System.Collections.Generic
  • using System.Text
  • using System.Net
  • using System.Net.Sockets
  • namespace SocketReuseAddress
  • class Program
  • static void Main(string args)
  • try
  • //Establish the local endpoint
    for the socket
  • IPEndPoint ipEndPoint new
    IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).Add
    ressList0, 11000)
  • //Create a TCP/IP Socket
  • Socket sListener new
    Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp)

46
ReuseAddress (fixed)
  • using System
  • using System.Collections.Generic
  • using System.Text
  • using System.Net
  • using System.Net.Sockets
  • namespace SocketReuseAddress
  • class Program
  • static void Main(string args)
  • try
  • //Establish the local endpoint
    for the socket
  • IPEndPoint ipEndPoint new
    IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).Add
    ressList0, 11000)
  • //Create a TCP/IP Socket
  • Socket sListener new
    Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp)

47
Linger
  • Linger (from dictionary.com)
  • v. lingered, lingering, lingers v. intr.
  • To be slow in leaving, especially out of
    reluctance tarry. See Synonyms at stay1.
  • To remain feebly alive for some time before
    dying.
  • To persist an aftertaste that lingers.
  • To proceed slowly saunter.
  • To be tardy in acting procrastinate.
  • v. tr.
  • To pass (a period of time) in a leisurely or
    aimless manner.
  • Linger has an enumeration, called LingerOption

48
Linger
  • // Send operations will time-out if
    //confirmation is not received within 1000
    //milliseconds.
  • s.SetSocketOption (SocketOptionLevel.Socket,
    SocketOptionName.SendTimeout, 1000)
  • // The socket will linger for 10 seconds //after
    Socket.Close is called.
  • LingerOption lingerOption new LingerOption
    (true, 10)
  • s.SetSocketOption (SocketOptionLevel.Socket,
    SocketOptionName.Linger, lingerOption)

49
Basic Outline
  • An Overview of Sockets
  • Working with Sockets in .NET
  • Asynchronous Programming
  • Socket Permissions

50
Asynchronous Programming
  • Introduction
  • Creating an Asynchronous Client Application
  • Creating an Asynchronous Server Application

51
Asynchronous Programming
  • Most socket functions
  • Indefinite time to complete
  • Blocked
  • Asynchronous programming
  • Functions that cant afford to hang around
  • A connection does not block an application
  • Events can be..
  • Signalled
  • Non-signalled

52
Asynchronous Programming
  • Two event types
  • Automatic (set themselves back to non-signalled
    state when they are signalled)
  • Manual (stay signalled until manually reset to
    non-signalled state)
  • ManualResetEvent use to indicate that you want
    your program to continue
  • The .NET Framework provides a delegate class for
    asynchronous operations.
  • The class is called AsyncCallback

53
Asynchronous Programming
  • Introduction
  • Creating an Asynchronous Client Application
  • Creating an Asynchronous Server Application

54
The flow of an asynchronous client application
Original Thread
Secondary Thread
Create Socket
Initialise Connection Request BeginConnect
Waiting
ConnectCallBack()
Initialise Sending Request BeginSend
Waiting
SendCallBack()
Initialise Receiving Request BeginReceive
Waiting and further processing
ReceiveCallback()
Close Socket
55
Asynchronous Client
  • using System
  • using System.Net
  • using System.Net.Sockets
  • using System.Text
  • using System.Threading
  • namespace AsyncClientExample
  • /// ltsummarygt
  • /// Summary description for Class1.
  • /// lt/summarygt
  • public class AsyncClient
  • public static ManualResetEvent connectDone
    new ManualResetEvent( false )
  • public static ManualResetEvent sendDone new
    ManualResetEvent( false )
  • public static ManualResetEvent receiveDone
    new ManualResetEvent( false )
  • public static string response string.Empty
  • public static string sb string.Empty

56
Asynchronous Client
  • //ConnectCallback is called when connection is
    ready
  • public static void ConnectCallback( IAsyncResult
    a )
  • Thread thr Thread.CurrentThread
  • Console.WriteLine( "ConnectCallback Thread
    State " thr.ThreadState )
  • Socket sktClient (Socket) a.AsyncState
  • sktClient.EndConnect( a )
  • Console.WriteLine("Socket connected to 0",
    sktClient.RemoteEndPoint.ToString() )
  • //Signal connectDone event to inform other
    thread
  • //that connection is ready for use
  • connectDone.Set()
  • //End public static void ConnectCallback(
    IAsyncResult a )

57
Asynchronous Client
  • //SendCallback is called when sending is complete
  • public static void SendCallback( IAsyncResult a )
  • Thread thr Thread.CurrentThread
  • Console.WriteLine( "SendCallback Thread State "
    thr.ThreadState )
  • Socket sktClient (Socket) a.AsyncState
  • int bytesSent sktClient.EndSend( a )
  • Console.WriteLine( "Sent 0 bytes to server",
    bytesSent )
  • //Signal sentDone event
  • sendDone.Set()
  • //End public static void SendCallback(
    IAsyncResult a )

58
Asynchronous Client
  • //ReceiveCallback is called when receiving is
    complete
  • public static void ReceiveCallback( IAsyncResult
    a )
  • Thread thr Thread.CurrentThread
  • Console.WriteLine( "ReceiveCallback Thread
    State " thr.ThreadState )
  • Socket sktClient (Socket) a.AsyncState
  • int bytesRead sktClient.EndReceive( a )
  • if( bytesRead gt 0 )
  • sb Encoding.ASCII.GetString(buffer,0,
    bytesRead)
  • sktClient.BeginReceive( buffer, 0,
    buffer.Length, 0, new AsyncCallback(
    ReceiveCallback), sktClient )
  • else
  • //Signal receiveDone event
  • receiveDone.Set()
  • //End public static void receiveCallback(
    IAsyncResult a )

59
Asynchronous Client
  • STAThread
  • static void Main(string args)
  • try
  • Thread thr Thread.CurrentThread
  • Console.WriteLine( "Main Thread State "
    thr.ThreadState )
  • IPHostEntry ipHost Dns.Resolve( "127.0.0.1"
    )
  • IPAddress ipAddr ipHost.AddressList0
  • IPEndPoint endPoint new IPEndPoint( ipAddr,
    11000 )
  • Socket sktClient new Socket(
    AddressFamily.InterNetwork,
  • SocketType.Stream,ProtocolType.Tcp )

60
Asynchronous Client
  • //Create new thread to initiate the connection
    to //the server
  • sktClient.BeginConnect( endPoint, new
    AsyncCallback( ConnectCallback ), sktClient )
  • connectDone.WaitOne()
  • string data "This is a test"
  • for( int i 0 i lt 72 i )
  • data i.ToString() "" (new string( '',
    i ))
  • byte byteData Encoding.ASCII.GetBytes( data
    "." )
  • //Send data in a separate thread
  • sktClient.BeginSend( byteData, 0,
    byteData.Length, SocketFlags.None, new
    AsyncCallback( SendCallback ), sktClient )

61
Asynchronous Client
  • //Do something in the main thread
  • byte byteData Encoding.ASCII.GetBytes( data
    "." )
  • //Send data in a separate thread
  • sktClient.BeginSend( byteData, 0,
    byteData.Length, SocketFlags.None,
  • new AsyncCallback( SendCallback ), sktClient )
  • //Do something in the main thread
  • for( int i 0 i lt 10 i )
  • Console.WriteLine( i )
  • Thread.Sleep( 10 )
  • //Wait until all sending is done
  • sendDone.WaitOne()

62
Asynchronous Client
  • //Start receiving data in a separate thread
  • sktClient.BeginReceive( buffer, 0,
    buffer.Length, SocketFlags.None,
  • new AsyncCallback( ReceiveCallback ),
    sktClient )
  • receiveDone.WaitOne()
  • Console.WriteLine( "Response received 0 ",
    sb )
  • sktClient.Shutdown( SocketShutdown.Both )
  • sktClient.Close()
  • catch( Exception e )
  • Console.WriteLine( e.ToString() )
  • Console.ReadLine()
  • //End Main
  • //End Class

63
Asynchronous Programming
  • Introduction
  • Creating an Asynchronous Client Application
  • Creating an Asynchronous Server Application

64
Asynchronous Server
  • using System
  • using System.Net
  • using System.Net.Sockets
  • using System.Text
  • using System.Threading
  • namespace AsyncServerExample
  • /// ltsummarygt
  • /// Summary description for Class1.
  • /// lt/summarygt
  • class AsyncServer
  • //Buffer to send and receive data
  • public static byte buffer new byte8192
  • //Event class to support synchronization
  • public static ManualResetEvent socketEvent
    new ManualResetEvent( false )

65
  • STAThread
  • static void Main(string args)
  • Console.WriteLine( "Main Thread ID "
    AppDomain.GetCurrentThreadId() )
  • byte bytes new byte8192
  • IPHostEntry ipHost Dns.Resolve(
    Dns.GetHostName() )
  • IPAddress ipAddr ipHost.AddressList0
  • IPEndPoint localEnd new IPEndPoint( ipAddr,
    11000 )
  • Socket sListener new Socket(
    AddressFamily.InterNetwork, SocketType.Stream,
    ProtocolType.Tcp )
  • //Bind socket
  • sListener.Bind( localEnd)
  • //Start listening
  • sListener.Listen( 10 )
  • Console.WriteLine( "Waiting for a
    connection....." )
  • AsyncCallback aCallback new AsyncCallback(
    AcceptCallback )
  • //Asynchronous method for accepting connections
  • sListener.BeginAccept( aCallback, sListener )
  • //Waiting for other threads to finish

66
Method AcceptCallBack
  • public static void AcceptCallback( IAsyncResult
    ar )
  • Console.WriteLine( "AcceptCallback Thread ID "
  • AppDomain.GetCurrentThreadId() )
  • //Retrieved the socket
  • Socket listener (Socket) ar.AsyncState
  • //New socket
  • Socket handler listener.EndAccept( ar )
  • handler.BeginReceive( buffer, 0, buffer.Length,
    0,
  • new AsyncCallback( ReceivCallback), handler )
  • //End public static void AcceptCallback(
    IAsyncResult ar )

67
  • public static void ReceiveCallback( IAsyncResult
    ar )
  • Console.WriteLine( "ReceiveCallback Thread ID
    " AppDomain.GetCurrentThreadId() )
  • string content string.Empty
  • Socket handler (Socket) ar.AsyncState
  • int bytesRead handler.EndReceive( ar )
  • //check for data
  • if( bytesRead gt 0 )
  • //Append data to main string
  • content Encoding.ASCII.GetString( buffer, 0,
    bytesRead )
  • //If end of message character is encountered
  • if( content.IndexOf( "." ) gt -1 )
  • Console.WriteLine( "Read 0 bytes from
    socket. \n Data 1",content.Length, content )
  • byte byteData Encoding.ASCII.GetBytes(
    content )
  • //Send data back to the client

68
  • public static void SendCallback( IAsyncResult
    ar )
  • Console.WriteLine( "SendCallback Thread ID "
  • AppDomain.GetCurrentThreadId() )
  • Socket handler (Socket) ar.AsyncState
  • //Send Data back to client
  • int bytesSent handler.EndSend( ar )
  • Console.WriteLine( "Sent 0 bytes to Client.
    ", bytesSent )
  • handler.Shutdown( SocketShutdown.Send )
  • handler.Close()
  • //Set main thread event
  • socketEvent.Set()
  • //End public static void SendCallback(
    IAsyncResult ar )

69
Basic Outline
  • An Overview of Sockets
  • Working with Sockets in .NET
  • Asynchronous Programming
  • Socket Permissions

70
Socket Permissions
  • Introduction
  • Using Imperative Security
  • Using Declarative Security

71
Socket Permissions
  • Help develop secure code
  • Only the code that has permission to run in the
    current context can be executed
  • Each code-access permission demonstrates one of
    the following rights
  • The right to access protected resources such as
    files
  • The right to perform a protected operation such
    as accessing managed code
  • SocketPermission class
  • enforces code-access permissions
  • Used to control rights to make or accept
    connections (control connections via sockets)
  • Consists of host specification and a set of
    actions specifying ways to connect to the host
  • Enforces secure code by monitoring the values of
    the host name, IP address and transport protocol

72
Socket Permissions
  • There are two ways to enforce security permission
    in C sockets
  • Imperatively
  • Implements permissions by creating a new instance
    of the SocketPermission class to demand a
    particular permission when the code is executed,
    such as the right to make a TCP connection. It
    is generally used when the security setting are
    changed at runtime.
  • Declaratively
  • Declarative syntax uses attributes to place
    security information into the metadata of your
    code, so that the client calls your code can use
    reflection to see what permissions are required
    by the code.

73
Imperative Security
  • Creates a new instance of the SocketPermission
    class to enforce security
  • Use imperative security syntax to perform demands
    and overrides, but not requests
  • Before calling the corresponding security
    measure, it is necessary to initialise the state
    of the SocketPermission class through the
    constructor so that it represents the particular
    form of permission that you want to use.
  • This kind of security is only useful when you
    have some information needed for security that is
    available only at runtime for example if you
    want to secure some host over a port but dont
    know the host name and port number until the
    program executes

74
Imperative Security
  • using System
  • using System.Collections.Generic
  • using System.Text
  • using System.Net
  • using System.Net.Sockets
  • using System.Security
  • using System.Security.Permissions
  • namespace SocketsImperativeSecurity
  • class Program
  • static void Main(string args)
  • //Option could be either Assert or
    Deny passed on the command line
  • //If option is Assert, then the
    program executes successfully
  • //Otherwise, it triggers a
    SecurityException
  • string option null

75
  • public static void MethodA(string option)
  • Console.WriteLine("Method A")
  • IPHostEntry ipHost
    Dns.GetHostEntry("127.0.0.1")
  • IPAddress ipAddress
    ipHost.AddressList0
  • IPEndPoint ipEndPoint new
    IPEndPoint(ipAddress, 11000)
  • Socket sender new
    Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp)
  • SocketPermission permitSocket new
    SocketPermission(NetworkAccess.Connect,
    TransportType.Tcp, "127.0.0.1",
    SocketPermission.AllPorts)
  • //Select assert or deny on the basis
    of paramter passed
  • if (option.Equals("deny"))
  • permitSocket.Deny()
  • else
  • permitSocket.Assert()
  • try
  • //Connect the socket to the
    romote endpoint. Catch an errors
  • sender.Connect(ipEndPoint)
  • Console.WriteLine("Socket
    connected to 0.", sender.RemoteEndPoint.ToString
    ())
  • byte bytes new byte1024

76
  • Console.WriteLine("Echoed Test
    0", Encoding.ASCII.GetString(bytes, 0,
    bytesRec))
  • catch (SocketException s)
  • Console.WriteLine("Socket
    Exception " s.ToString())
  • catch (SecurityException se)
  • Console.WriteLine("Socket
    Exception " se.ToString())
  • //end of catch
  • finally
  • if (sender.Connected)
  • //Release the socket
  • sender.Shutdown(SocketShutdown
    .Both)
  • sender.Close()

77
Declarative Security
  • Uses .NET attributes to place security
    information inside the metadata of the code
  • Attributes can be placed at the assembly, class
    or member level to indicate the type of request,
    demand, or override that is needed.
  • In order to use this security syntax, the state
    of the data must be initialised first for the
    SocketPermissionAttribute object through the
    declarative syntax, so that it represents the
    form of permission that is being enforced on the
    code.

78
Declarative Security
  • using System
  • using System.Collections.Generic
  • using System.Text
  • using System.Net
  • using System.Net.Sockets
  • using System.Security
  • using System.Security.Permissions
  • namespace SocketDeclarativeSecurity
  • class Program
  • static void Main(string args)
  • LegalMethod()
  • IllegalMethod()
  • Console.Write("Press a key to
    continue.")
  • Console.ReadLine()

79
Legal Method
  • SocketPermission (SecurityAction.Assert, Access
    "Connect", Host "127.0.0.1", Port "All",
    Transport "Tcp")
  • public static void LegalMethod()
  • Console.WriteLine("Legal Method")
  • IPHostEntry ipHost Dns.GetHostEntry("127.0.0.1"
    )
  • IPAddress ipAddr ipHost.AddressList0
  • IPEndPoint ipEndPoint new IPEndPoint(ipAddr,
    11000)
  • Socket sender new Socket(AddressFamily.InterNet
    work, SocketType.Stream, ProtocolType.Tcp)
  • try
  • //Connect the socket to the remote endpoint.
    Catch any errors
  • sender.Connect(ipEndPoint)
  • Console.WriteLine("Socket
    connected to 0", sender.RemoteEndPoint.ToString(
    ))
  • //end of try
  • catch (SecurityException se)
  • Console.WriteLine("Security
    Exception " se)
  • //end of catch
  • catch (SocketException se)

80
Illegal Method
  • SocketPermission(SecurityAction.Deny,
    Access "Connect", Host "127.0.0.1", Port
    "All", Transport "Tcp")
  • public static void IllegalMethod()
  • Console.WriteLine("Illegal Method")
  • IPHostEntry ipHost
    Dns.GetHostEntry("127.0.0.1")
  • IPAddress ipAddr ipHost.AddressList
    0
  • IPEndPoint ipEndPoint new
    IPEndPoint(ipAddr, 11000)
  • Socket sender new
    Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp)
  • try
  • //Connect the socket to the
    remote endpoint. Catch any errors
  • sender.Connect(ipEndPoint)
  • Console.WriteLine("Socket
    connected to 0", sender.RemoteEndPoint.ToString(
    ))
  • //end of try
  • catch (SecurityException se)
  • Console.WriteLine("Security
    Exception " se)
  • //end of catch

81
Summary
  • Socket class
  • Two main socket types
  • Stream sockets
  • Datagram sockets
  • System.Net.Sockets namespace
  • SocketException Class
  • Finally block should contain Close and Shutdown
    methods
  • Basic socket options
  • Asynchronous programming model
  • Security
  • Imperative
  • Permissions known only at runtime
  • Declarative
  • Permissions needed are known at compile-time
Write a Comment
User Comments (0)
About PowerShow.com