System.Net.Sockets.Socket Class

public class Socket : IDisposable

Base Types

Object
  Socket

This type implements IDisposable.

Assembly

System

Library

Networking

Summary

Creates a communication endpoint through which an application sends or receives data across a network.

Description

This class enables a Socket instance to communicate with another socket across a network. The communication can be through connection-oriented and connectionless protocols using either data streams or datagrams (discrete message packets).

Message-oriented protocols preserve message boundaries and require that for each System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method call there is one corresponding System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method call. For stream-oriented protocols, data is transmitted without regards to message boundaries. In this case, for example, multiple System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method calls might be necessary to retrieve all the data from one System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method call. The protocol is set in the Socket class constructor.

A Socket instance has a local and a remote endpoint associated with it. The local endpoint contains the connection information for the current socket instance. The remote endpoint contains the connection information for the socket that the current instance communicates with. The endpoints are required to be an instance of a type derived from the EndPoint class. For the Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) protocols, an endpoint includes the address family, an Internet Protocol (IP) address, and a port number. For connection-oriented protocols (for example, TCP), the remote endpoint does not have to be specified when transferring data. For connectionless protocols (for example, UDP), the remote endpoint is required to be specified.

Methods are provided for both synchronous and asynchronous operations. A synchronous method can operate in blocking mode, in which it waits (blocks) until the operation is complete before returning, or in non-blocking mode, where it returns immediately, possibly before the operation has completed. The blocking mode is set through the System.Net.Sockets.Socket.Blocking property.

An asynchronous method returns immediately and, by convention, relies on a delegate to complete the operation. Asynchronous methods have names which correspond to their synchronous counterparts prefixed with either 'Begin' or End'. For example, the synchronous System.Net.Sockets.Socket.Accept method has asynchronous counterpart methods named System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) and System.Net.Sockets.Socket.EndAccept(System.IAsyncResult). The example for the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method shows the basic steps for using an asynchronous operation. A complete working example follows this discussion.

Connection-oriented protocols commonly use the client/server model. In this model, one of the sockets is set up as a server, and one or more sockets are set up as clients. A general procedure demonstrating the synchronous communication process for this model is as follows.

On the server-side:

  1. Create a socket to listen for incoming connection requests.
  2. Set the local endpoint using the System.Net.Sockets.Socket.Bind(System.Net.EndPoint) method.
  3. Put the socket in the listening state using the System.Net.Sockets.Socket.Listen(System.Int32) method.
  4. At this point incoming connection requests from a client are placed in a queue.
  5. Use the System.Net.Sockets.Socket.Accept method to create a server socket for a connection request issued by a client-side socket. This sets the remote endpoint.
  6. Use the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) and System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) methods to communicate with the client socket.
  7. When communication is finished, terminate the connection using the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method.
  8. Release the resources allocated by the server socket using the System.Net.Sockets.Socket.Close method.
  9. Release the resources allocated by the listener socket using the System.Net.Sockets.Socket.Close method.
On the client-side:

  1. Create the client socket.
  2. Connect to the server socket using the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method. This sets both the local and remote endpoints for the client socket.
  3. Use the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) and System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) methods to communicate with the server socket.
  4. When communication is finished, terminate the connection using the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method.
  5. Release the resources allocated by the client socket using the System.Net.Sockets.Socket.Close method.
The shutdown step in the previous procedure is not necessary but ensures that any pending data is not lost. If the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method is not called, the System.Net.Sockets.Socket.Close method shuts down the connection either gracefully or by force. A graceful closure attempts to transfer all pending data before the connection is terminated. Use the System.Net.Sockets.SocketOptionName.Linger socket option to specify a graceful closure for a socket.

[Note: This implementation is based on the UNIX sockets implementation in the Berkeley Software Distribution (BSD, release 4.3) from the University of California at Berkeley.

]

Example

The following examples provide a client/server application that demonstrates the use of asynchronous communication between sockets. Run the client and server on different consoles.

The following code is for the server application. Start this application before the client application.

using System;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class Server 
{
  // used to pass state information to delegate
  internal class StateObject 
  {
    internal byte[] sBuffer;
    internal Socket sSocket;
    internal StateObject(int size, Socket sock) {
      sBuffer = new byte[size];
      sSocket = sock;
    }
  }
  static void Main() 
  {
    IPAddress ipAddress =
      Dns.Resolve( Dns.GetHostName() ).AddressList[0];

    IPEndPoint ipEndpoint =
      new IPEndPoint(ipAddress, 1800);

    Socket listenSocket =
      new Socket(AddressFamily.InterNetwork,
                 SocketType.Stream,
                 ProtocolType.Tcp);

    listenSocket.Bind(ipEndpoint);
    listenSocket.Listen(1);
    IAsyncResult asyncAccept = listenSocket.BeginAccept(
      new AsyncCallback(Server.acceptCallback),
      listenSocket );

    // could call listenSocket.EndAccept(asyncAccept) here
    // instead of in the callback method, but since 
    // EndAccept blocks, the behavior would be similar to 
    // calling the synchronous Accept method

    Console.Write("Connection in progress.");
    if( writeDot(asyncAccept) == true ) 
    {
      // allow time for callbacks to
      // finish before the program ends 
      Thread.Sleep(3000);
    }
  }

  public static void
    acceptCallback(IAsyncResult asyncAccept) {
      Socket listenSocket = (Socket)asyncAccept.AsyncState;
      Socket serverSocket =
        listenSocket.EndAccept(asyncAccept);

      // arriving here means the operation completed
      // (asyncAccept.IsCompleted = true) but not
      // necessarily successfully
      if( serverSocket.Connected == false )
      {
        Console.WriteLine( ".server is not connected." );
        return;
      }
      else Console.WriteLine( ".server is connected." );

      listenSocket.Close();

      StateObject stateObject =
        new StateObject(16, serverSocket);

      // this call passes the StateObject because it 
      // needs to pass the buffer as well as the socket
      IAsyncResult asyncReceive =
        serverSocket.BeginReceive(
          stateObject.sBuffer,
          0,
          stateObject.sBuffer.Length,
          SocketFlags.None,
          new AsyncCallback(receiveCallback),
          stateObject);

      Console.Write("Receiving data.");
      writeDot(asyncReceive);
  }

  public static void
    receiveCallback(IAsyncResult asyncReceive) {
      StateObject stateObject =
        (StateObject)asyncReceive.AsyncState;
      int bytesReceived =
        stateObject.sSocket.EndReceive(asyncReceive);

      Console.WriteLine(
        ".{0} bytes received: {1}",
        bytesReceived.ToString(),
        Encoding.ASCII.GetString(stateObject.sBuffer) );

      byte[] sendBuffer =
        Encoding.ASCII.GetBytes("Goodbye");
      IAsyncResult asyncSend =
        stateObject.sSocket.BeginSend(
          sendBuffer,
          0,
          sendBuffer.Length,
          SocketFlags.None,
          new AsyncCallback(sendCallback),
          stateObject.sSocket);

      Console.Write("Sending response.");
      writeDot(asyncSend);
  }

  public static void sendCallback(IAsyncResult asyncSend) {
    Socket serverSocket = (Socket)asyncSend.AsyncState;
    int bytesSent = serverSocket.EndSend(asyncSend);
    Console.WriteLine(
      ".{0} bytes sent.{1}{1}Shutting down.",
      bytesSent.ToString(),
      Environment.NewLine );

    serverSocket.Shutdown(SocketShutdown.Both);
    serverSocket.Close();
  }

  // times out after 20 seconds but operation continues
  internal static bool writeDot(IAsyncResult ar)
  {
    int i = 0;
    while( ar.IsCompleted == false ) 
    {
      if( i++ > 40 ) 
      {
        Console.WriteLine("Timed out.");
        return false;
      }
      Console.Write(".");
      Thread.Sleep(500);
    }
    return true;
  }
}
   
The following code is for the client application. When starting the application, supply the hostname of the console running the server application as an input parameter (for example, ProgramName hostname ).

using System;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class Client {

  // used to pass state information to delegate
  class StateObject 
  {
    internal byte[] sBuffer;
    internal Socket sSocket;
    internal StateObject(int size, Socket sock) {
      sBuffer = new byte[size];
      sSocket = sock;
    }
  }

  static void Main(string[] argHostName) 
  {
    IPAddress ipAddress =
      Dns.Resolve( argHostName[0] ).AddressList[0];

    IPEndPoint ipEndpoint =
      new IPEndPoint(ipAddress, 1800);

    Socket clientSocket = new Socket(
      AddressFamily.InterNetwork,
      SocketType.Stream,
      ProtocolType.Tcp);

    IAsyncResult asyncConnect = clientSocket.BeginConnect(
      ipEndpoint,
      new AsyncCallback(connectCallback),
      clientSocket );

    Console.Write("Connection in progress.");
    if( writeDot(asyncConnect) == true ) 
    {
      // allow time for callbacks to
      // finish before the program ends
      Thread.Sleep(3000);
    }
  }

  public static void
    connectCallback(IAsyncResult asyncConnect) {
      Socket clientSocket =
        (Socket)asyncConnect.AsyncState;
      clientSocket.EndConnect(asyncConnect);
      // arriving here means the operation completed
      // (asyncConnect.IsCompleted = true) but not
      // necessarily successfully
      if( clientSocket.Connected == false )
      {
        Console.WriteLine( ".client is not connected." );
        return;
      }
      else Console.WriteLine( ".client is connected." );

      byte[] sendBuffer = Encoding.ASCII.GetBytes("Hello");
      IAsyncResult asyncSend = clientSocket.BeginSend(
        sendBuffer,
        0,
        sendBuffer.Length,
        SocketFlags.None,
        new AsyncCallback(sendCallback),
        clientSocket);

      Console.Write("Sending data.");
      writeDot(asyncSend);
  }

  public static void sendCallback(IAsyncResult asyncSend) 
  {
    Socket clientSocket = (Socket)asyncSend.AsyncState;
    int bytesSent = clientSocket.EndSend(asyncSend);
    Console.WriteLine(
      ".{0} bytes sent.",
      bytesSent.ToString() );

    StateObject stateObject =
      new StateObject(16, clientSocket);

    // this call passes the StateObject because it
    // needs to pass the buffer as well as the socket
    IAsyncResult asyncReceive =
      clientSocket.BeginReceive(
        stateObject.sBuffer,
        0,
        stateObject.sBuffer.Length,
        SocketFlags.None,
        new AsyncCallback(receiveCallback),
        stateObject);

    Console.Write("Receiving response.");
    writeDot(asyncReceive);
  }

  public static void
    receiveCallback(IAsyncResult asyncReceive) {
      StateObject stateObject =
       (StateObject)asyncReceive.AsyncState;

      int bytesReceived =
        stateObject.sSocket.EndReceive(asyncReceive);

      Console.WriteLine(
        ".{0} bytes received: {1}{2}{2}Shutting down.",
        bytesReceived.ToString(),
        Encoding.ASCII.GetString(stateObject.sBuffer),
        Environment.NewLine );

      stateObject.sSocket.Shutdown(SocketShutdown.Both);
      stateObject.sSocket.Close();
  }

  // times out after 2 seconds but operation continues
  internal static bool writeDot(IAsyncResult ar)
  {
    int i = 0;
    while( ar.IsCompleted == false ) 
    {
      if( i++ > 20 ) 
      {
        Console.WriteLine("Timed out.");
        return false;
      }
      Console.Write(".");
      Thread.Sleep(100);
    }
    return true;
  }
}
   
The output of the server application is

Connection in progress...........server is connected.

Receiving data......5 bytes received: Hello

Sending response....7 bytes sent.

Shutting down.

-----------------------------------------

The output of the client application is

Connection in progress......client is connected.

Sending data......5 bytes sent.

Receiving response......7 bytes received: Goodbye

Shutting down.

See Also

System.Net.Sockets Namespace

Members

Socket Constructors

Socket Constructor

Socket Methods

Socket.Accept Method
Socket.BeginAccept Method
Socket.BeginConnect Method
Socket.BeginReceive Method
Socket.BeginReceiveFrom Method
Socket.BeginSend Method
Socket.BeginSendTo Method
Socket.Bind Method
Socket.Close Method
Socket.Connect Method
Socket.Dispose Method
Socket.EndAccept Method
Socket.EndConnect Method
Socket.EndReceive Method
Socket.EndReceiveFrom Method
Socket.EndSend Method
Socket.EndSendTo Method
Socket.Finalize Method
Socket.GetHashCode Method
Socket.GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName) Method
Socket.GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, byte[]) Method
Socket.GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, int) Method
Socket.IOControl Method
Socket.Listen Method
Socket.Poll Method
Socket.Receive(byte[], int, System.Net.Sockets.SocketFlags) Method
Socket.Receive(byte[], System.Net.Sockets.SocketFlags) Method
Socket.Receive(byte[], int, int, System.Net.Sockets.SocketFlags) Method
Socket.Receive(byte[]) Method
Socket.ReceiveFrom(byte[], System.Net.EndPoint&) Method
Socket.ReceiveFrom(byte[], System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method
Socket.ReceiveFrom(byte[], int, System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method
Socket.ReceiveFrom(byte[], int, int, System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method
Socket.Select Method
Socket.Send(byte[], int, int, System.Net.Sockets.SocketFlags) Method
Socket.Send(byte[]) Method
Socket.Send(byte[], System.Net.Sockets.SocketFlags) Method
Socket.Send(byte[], int, System.Net.Sockets.SocketFlags) Method
Socket.SendTo(byte[], System.Net.EndPoint) Method
Socket.SendTo(byte[], System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method
Socket.SendTo(byte[], int, System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method
Socket.SendTo(byte[], int, int, System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method
Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, System.Object) Method
Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, byte[]) Method
Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, int) Method
Socket.Shutdown Method
Socket.System.IDisposable.Dispose Method

Socket Properties

Socket.AddressFamily Property
Socket.Available Property
Socket.Blocking Property
Socket.Connected Property
Socket.Handle Property
Socket.LocalEndPoint Property
Socket.ProtocolType Property
Socket.RemoteEndPoint Property
Socket.SocketType Property


Socket Constructor

public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);

Summary

Constructs and initializes a new instance of the Socket class.

Parameters

addressFamily
One of the values defined in the AddressFamily enumeration.
socketType
One of the values defined in the SocketType enumeration.
protocolType
One of the values defined in the ProtocolType enumeration.

Exceptions

Exception TypeCondition
SocketExceptionThe combination of addressFamily, socketType, and protocolType is invalid.

-or-

An error occurred while creating the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

Description

The addressFamily parameter specifies the addressing scheme used by the current instance, the socketType parameter specifies the socket type of the current instance, and the protocolType parameter specifies the protocol used by the current instance. The three parameters are not independent. Some address families restrict which protocols are used, and often the socket type is determined by the protocol. When the specified values are not a valid combination, a SocketException exception is thrown.

Using the Unknown member of either the AddressFamily or ProtocolType enumeration, results in a SocketException exception being thrown.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Accept Method

public Socket Accept();

Summary

Creates and initializes a new Socket instance and connects it to an incoming connection request.

Return Value

A new connected Socket instance.

Exceptions

Exception TypeCondition
InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionAn error occurred while accessing the listening socket or while creating the new socket.

-or-

The System.Net.Sockets.Socket.Blocking property is set to false .

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is used only on the server-side of connection-oriented protocols. It extracts the first connection request from the queue of pending requests, creates a new Socket instance, and connects this instance to the socket associated with the request.

The System.Net.Sockets.Socket.Blocking property of the socket determines the behavior of this method when there are no pending connection requests. When false , this method will throw a SocketException. When true , this method blocks.

The following properties of the new Socket instance returned by this method have values identical to the corresponding properties of the current instance:

The System.Net.Sockets.Socket.RemoteEndPoint property of the new instance is set to the local endpoint of the first request in the input queue. The System.Net.Sockets.Socket.Connected property is set to true .

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.BeginAccept Method

public IAsyncResult BeginAccept(AsyncCallback callback, object state);

Summary

Begins an asynchronous operation to accept an incoming connection request.

Parameters

callback
A AsyncCallback delegate, or null .
state
An application-defined object, or null .

Return Value

A IAsyncResult instance that contains information about the asynchronous operation.

Exceptions

Exception TypeCondition
SocketExceptionAn error occurred while accepting the connection. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.

[Note: The System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method.]

If the callback parameter is not null , the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method.

The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.

To determine the connection status, check the System.Net.Sockets.Socket.Connected property, or use either the System.Net.Sockets.Socket.Poll(System.Int32,System.Net.Sockets.SelectMode) or System.Net.Sockets.Socket.Select(System.Collections.IList,System.Collections.IList,System.Collections.IList,System.Int32) method.

[Note: For more information, see System.Net.Sockets.Socket.Accept, the synchronous version of this method.

]

Example

The following excerpt from the Socket class overview example outlines an asynchronous accept operation.

public class Server
{
  static void Main()
  {
    .
    .
    .
    listenSocket.BeginAccept(
      new AsyncCallback(Server.acceptCallback),
      listenSocket);
    .
    .
    .
    // EndAccept can be called here
    .
    .
    .
  }

  public static void
    acceptCallback(IAsyncResult asyncAccept)
  {
    Socket listenSocket =
      (Socket)asyncAccept.AsyncState;

    Socket serverSocket =
      listenSocket.EndAccept(asyncAccept);

    serverSocket.BeginReceive(...);
    .
    .
    .
  }
}

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.BeginConnect Method

public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state);

Summary

Begins an asynchronous operation to associate the current instance with a remote endpoint.

Parameters

remoteEP
The EndPoint associated with the socket to connect to.

callback
A AsyncCallback delegate, or null .
state
An application-defined object, or null .

Return Value

A IAsyncResult instance that contains information about the asynchronous operation.

Exceptions

Exception TypeCondition
ArgumentNullExceptionremoteEP is null .

SocketExceptionAn error occurred while making the connection. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.
SecurityExceptionA caller higher in the call stack does not have permission for the requested operation.

Description

To release resources allocated by the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.

[Note: The System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method.]

If the callback parameter is not null , the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method.

The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.

To determine the connection status, check the System.Net.Sockets.Socket.Connected property, or use either the System.Net.Sockets.Socket.Poll(System.Int32,System.Net.Sockets.SelectMode) or System.Net.Sockets.Socket.Select(System.Collections.IList,System.Collections.IList,System.Collections.IList,System.Int32) method.

[Note: For more information, see System.Net.Sockets.Socket.Connect(System.Net.EndPoint), the synchronous version of this method.

]

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.BeginReceive Method

public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state);

Summary

Begins an asynchronous operation to receive data from a socket.

Parameters

buffer
A Byte array to store data received from the socket.
offset
A Int32 containing the zero-based position in buffer to begin storing the received data.
size
A Int32 containing the number of bytes to receive.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
callback
A AsyncCallback delegate, or null .
state
An application-defined object, or null .

Return Value

A IAsyncResult instance that contains information about the asynchronous operation.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionoffset < 0.

-or-

offset > buffer.Length.

-or-

size < 0.

-or-

size > buffer.Length - offset.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.

[Note: The System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method.]

If the callback parameter is not null , the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method.

The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.

[Note: For more information, see System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags), the synchronous version of this method.

]

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.BeginReceiveFrom Method

public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state);

Summary

Begins an asynchronous operation to receive data from a socket and, for connectionless protocols, store the endpoint associated with the socket that sent the data.

Parameters

buffer
A Byte array to store data received from the socket.
offset
A Int32 containing the zero-based position in buffer to begin storing the received data.
size
A Int32 containing the number of bytes to receive.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek .
remoteEP
An instance of a class derived from the EndPoint class, which contains the endpoint associated with the socket that sent the data.

callback
A AsyncCallback delegate, or null .
state
An application-defined object, or null .

Return Value

A IAsyncResult instance that contains information about the asynchronous operation.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .

-or-

remoteEP is null .

ArgumentOutOfRangeExceptionoffset < 0.

-or-

offset > buffer.Length.

-or-

size < 0.

-or-

size > buffer.Length - offset.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.
SecurityExceptionA caller in the call stack does not have the required permissions.

Description

To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method, and specify the IAsyncResult object returned by this method.

[Note: The System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method.]

If the callback parameter is not null , the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method.

The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.

[Note: For more information, see System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@), the synchronous version of this method.

]

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see Socket.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.BeginSend Method

public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state);

Summary

Begins an asynchronous operation to send data to a connected socket.

Parameters

buffer
A Byte array storing data to send to the socket.
offset
A Int32 containing the zero-based position in buffer containing the starting location of the data to send.
size
A Int32 containing the number of bytes to send.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand .
callback
A AsyncCallback delegate, or null .
state
An application-defined object, or null .

Return Value

A IAsyncResult instance that contains information about the asynchronous operation.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionoffset < 0.

-or-

offset > buffer.Length.

-or-

size < 0.

-or-

size > buffer.Length - offset.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.

[Note: The System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method.]

If the callback parameter is not null , the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method.

The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.

[Note: For more information, see System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags), the synchronous version of this method.

]

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.BeginSendTo Method

public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state);

Summary

Begins an asynchronous operation to send data to the socket associated with the specified endpoint.

Parameters

buffer
A Byte array storing data to send to the socket.
offset
A Int32 containing the zero-based position in buffer to begin sending data.
size
A Int32 containing the number of bytes to send.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand .
remoteEP
The EndPoint associated with the socket to receive the data.

callback
A AsyncCallback delegate, or null .
state
An application-defined object, or null .

Return Value

A IAsyncResult instance that contains information about the asynchronous operation.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .

-or-

remoteEP is null .

ArgumentOutOfRangeExceptionoffset < 0.

-or-

offset > buffer.Length.

-or-

size < 0.

-or-

size > buffer.Length - offset.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.
SecurityExceptionA caller in the call stack does not have the required permissions.

Description

To retrieve the results of the operation and release resources allocated by the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method, call the System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method, and specify the IAsyncResult object returned by this method.

[Note: The System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method should be called exactly once for each call to the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method.]

If the callback parameter is not null , the method referenced by callback is invoked when the asynchronous operation completes. The IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The method referenced by callback can retrieve the results of the operation by calling the System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method.

The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method.

[Note: For more information, see System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint), the synchronous version of this method.

]

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Bind Method

public void Bind(EndPoint localEP);

Summary

Associates the current instance with a local endpoint.

Parameters

localEP
The local EndPoint to be associated with the socket.

Exceptions

Exception TypeCondition
ArgumentNullExceptionlocalEP is null .
SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.
SecurityException A caller in the call stack does not have the required permission.

Description

This method sets the System.Net.Sockets.Socket.LocalEndPoint property of the current instance to localEP.

[Note: For connection-oriented protocols, this method is generally used only on the server-side and is required to be called before the first call to the System.Net.Sockets.Socket.Listen(System.Int32) method. On the client-side, binding is usually performed implicitly by the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method.

For connectionless protocols, the System.Net.Sockets.Socket.Connect(System.Net.EndPoint)System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint), and System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) methods bind the current instance to the local endpoint if the current instance has not previously been bound.

]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Close Method

public void Close();

Summary

Closes the current instance and releases all managed and unmanaged resources allocated by the current instance.

Description

This method calls the System.Net.Sockets.Socket.Dispose(System.Boolean)(Boolean) method with the argument set to true , which frees both managed and unmanaged resources used by the current instance.

The socket attempts to perform a graceful closure when the System.Net.Sockets.SocketOptionName.Linger socket option is enabled and set to a non-zero linger time. In all other cases, closure is forced and any pending data is lost.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Connect Method

public void Connect(EndPoint remoteEP);

Summary

Associates the current instance with a remote endpoint.

Parameters

remoteEP
The EndPoint associated with the socket to connect to.

Exceptions

Exception TypeCondition
ArgumentNullExceptionremoteEP is null .
InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.
SecurityException A caller in the call stack does not have the required permission.

Description

This method sets the System.Net.Sockets.Socket.RemoteEndPoint property of the current instance to remoteEP.

[Note: For connection-oriented protocols, this method establishes a connection between the current instance and the socket associated with remoteEP. This method is used only on the client-side. The System.Net.Sockets.Socket.Accept method establishes the connection on the server-side. Once the connection has been made, data can be sent using the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method, and received using the System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method.

For connectionless protocols, the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method can be used from both client and server-sides, allowing the use of the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method instead of the System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) method. The System.Net.Sockets.Socket.RemoteEndPoint property is set to remoteEP and the System.Net.Sockets.Socket.LocalEndPoint property is set to a value determined by the protocol; however, a connection is not established. Subsequent data is required to be received on the endpoint set in the System.Net.Sockets.Socket.LocalEndPoint property.

]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Dispose Method

protected virtual void Dispose(bool disposing);

Summary

Closes the current instance, releases the unmanaged resources allocated by the current instance, and optionally releases the managed resources.

Parameters

disposing
A Boolean. Specify true to release both managed and unmanaged resources; false to release only unmanaged resources.

Description

[Behaviors: This method closes the current Socket instance and releases all unmanaged resources allocated by the current instance. When disposing is true , this method also releases all resources held by any managed objects allocated by the current instance. ]

[Default: This method closes the current Socket instance but does not release any managed resources. ]

[Overrides: The System.Net.Sockets.Socket.Dispose(System.Boolean) method can be called multiple times by other objects. When overriding this method, do not reference objects that have been previously disposed in an earlier call. ]

[Usage: Use this method to release resources allocated by the current instance. ]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.EndAccept Method

public Socket EndAccept(IAsyncResult asyncResult);

Summary

Ends an asynchronous call to accept an incoming connection request.

Parameters

asyncResult
A IAsyncResult object that holds the state information for the asynchronous operation.

Return Value

A new connected Socket instance.

Exceptions

Exception TypeCondition
ArgumentNullExceptionasyncResult is null .
ArgumentExceptionasyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method.
InvalidOperationExceptionSystem.Net.Sockets.Socket.EndAccept(System.IAsyncResult) was previously called for this operation.
SocketExceptionAn error occurred during the operation. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method blocks if the asynchronous operation has not completed.

The System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method call that began the request.

If the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndAccept(System.IAsyncResult) method, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.EndConnect Method

public void EndConnect(IAsyncResult asyncResult);

Summary

Ends an asynchronous call to associate the current instance with a remote endpoint.

Parameters

asyncResult
A IAsyncResult object that holds the state information for the asynchronous operation.

Exceptions

Exception TypeCondition
ArgumentNullExceptionasyncResult is null .
ArgumentExceptionasyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method.
InvalidOperationExceptionSystem.Net.Sockets.Socket.EndConnect(System.IAsyncResult) was previously called for this operation.
SocketExceptionAn error occurred during the operation. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method blocks if the asynchronous operation has not completed.

The System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method call that began the request.

If the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginConnect(System.Net.EndPoint,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndConnect(System.IAsyncResult) method, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.EndReceive Method

public int EndReceive(IAsyncResult asyncResult);

Summary

Ends an asynchronous call to receive data from a socket.

Parameters

asyncResult
A IAsyncResult object that holds the state information for the asynchronous operation.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionasyncResult is null .
ArgumentExceptionasyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method.
InvalidOperationExceptionSystem.Net.Sockets.Socket.EndReceive(System.IAsyncResult) was previously called for this operation.
SocketExceptionAn error occurred during the operation. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method blocks if the asynchronous operation has not completed.

The System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method call that began the request.

If the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginReceive(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) method, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.EndReceiveFrom Method

public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint);

Summary

Ends an asynchronous call to receive data from a socket and store the endpoint associated with the socket that sent the data.

Parameters

asyncResult
A IAsyncResult object that holds the state information for the asynchronous operation.

endPoint
A reference to the EndPoint associated with the socket that sent the data.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionasyncResult is null .
ArgumentExceptionasyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method.
InvalidOperationExceptionSystem.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) was previously called for this operation.
SocketExceptionAn error occurred during the operation. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method blocks if the asynchronous operation has not completed.

The System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method call that began the request.

If the System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.EndSend Method

public int EndSend(IAsyncResult asyncResult);

Summary

Ends an asynchronous call to send data to a connected socket.

Parameters

asyncResult
A IAsyncResult object that holds the state information for the asynchronous operation.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionasyncResult is null .
ArgumentExceptionasyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method.
InvalidOperationExceptionSystem.Net.Sockets.Socket.EndSend(System.IAsyncResult) was previously called for this operation.
SocketExceptionAn error occurred during the operation. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method blocks if the asynchronous operation has not completed.

The System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method call that began the request.

If the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginSend(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, which uses the System.Net.Sockets.Socket.EndSend(System.IAsyncResult) method, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.EndSendTo Method

public int EndSendTo(IAsyncResult asyncResult);

Summary

Ends an asynchronous call to send data to a socket associated with a specified endpoint.

Parameters

asyncResult
A IAsyncResult object that holds the state information for the asynchronous operation.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionasyncResult is null .
ArgumentExceptionasyncResult was not returned by the current instance from a call to the System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) method.
InvalidOperationExceptionSystem.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) was previously called for this operation.
SocketExceptionAn error occurred during the operation. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method blocks if the asynchronous operation has not completed.

The System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method completes an asynchronous request that was started with a call to the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method. The object specified for the asyncResult parameter is required to be the same object as was returned by the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method call that began the request.

If the System.Net.Sockets.Socket.EndSendTo(System.IAsyncResult) method is invoked via the AsyncCallback delegate specified to the System.Net.Sockets.Socket.BeginSendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint,System.AsyncCallback,System.Object) method, the asyncResult parameter is the IAsyncResult argument passed to the delegate's method.

Example

For an outline of an asynchronous operation, see the System.Net.Sockets.Socket.BeginAccept(System.AsyncCallback,System.Object) method. For the complete example, see the Socket class overview.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Finalize Method

~Socket();

Summary

Closes the current instance and releases unmanaged resources allocated by the current instance.

Description

[Note: Application code does not call this method; it is automatically invoked during garbage collection unless finalization by the garbage collector has been disabled. For more information, see System.GC.SuppressFinalize(System.Object), and System.Object.Finalize.

This method calls System.Net.Sockets.NetworkStream.Dispose(System.Boolean)(false ) to free unmanaged resources used by the current instance.

This method overrides System.Object.Finalize.

]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.GetHashCode Method

public override int GetHashCode();

Summary

Generates a hash code for the current instance.

Return Value

A Int32 containing the hash code for the current instance.

Description

The algorithm used to generate the hash code is unspecified.

[Note: This method overrides System.Object.GetHashCode. ]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName) Method

public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName);

Summary

Retrieves an object containing the value of the specified socket option.

Parameters

optionLevel
One of the values defined in the SocketOptionLevel enumeration.
optionName
One of the values defined in the SocketOptionName enumeration.

Return Value

The following table describes the values returned by this method.

optionNameReturn value
Linger An instance of the LingerOption class.
AddMembership

-or-

DropMembership

An instance of the MulticastOption class.
All other values defined in the SocketOptionName enumeration.A Int32 containing the value of the option.

Exceptions

Exception TypeCondition
SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

Socket options determine the behavior of the current instance.

optionLevel and optionName are not independent. See the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel , SocketOptionName , Int32 ) method for a listing of the values of the SocketOptionName enumeration grouped by SocketOptionLevel.

Example

The following example gets the state of the linger option and the size of the receive buffer, changes the values of both, then gets the new values.

using System;
using System.Net.Sockets;

class OptionTest{

  public static void Main() {

    // Get the current option values.
    Socket someSocket =
      new Socket(AddressFamily.InterNetwork,
                 SocketType.Stream,
                 ProtocolType.Tcp);

    LingerOption lingerOp =
      (LingerOption)someSocket.GetSocketOption(
                    SocketOptionLevel.Socket,
                    SocketOptionName.Linger);

    int receiveBuffer =
      (int)someSocket.GetSocketOption(
           SocketOptionLevel.Socket,
           SocketOptionName.ReceiveBuffer);

    Console.WriteLine(
      "Linger option is {0} and set to {1} seconds.",
      lingerOp.Enabled.ToString(),
      lingerOp.LingerTime.ToString() );

    Console.WriteLine(
      "Size of the receive buffer is {0} bytes.",
      receiveBuffer.ToString() );

    // Change the options.
    lingerOp = new LingerOption(true, 10);
    someSocket.SetSocketOption(
      SocketOptionLevel.Socket,
      SocketOptionName.Linger,
      lingerOp);

    someSocket.SetSocketOption(
      SocketOptionLevel.Socket,
      SocketOptionName.ReceiveBuffer,
      2048);

    Console.WriteLine(
      "The SetSocketOption method has been called.");
 
    // Get the new option values.
    lingerOp =
      (LingerOption)someSocket.GetSocketOption(
                    SocketOptionLevel.Socket,
                    SocketOptionName.Linger);

    receiveBuffer =
      (int)someSocket.GetSocketOption(
           SocketOptionLevel.Socket,
           SocketOptionName.ReceiveBuffer);

    Console.WriteLine(
      "Linger option is now {0} and set to {1} seconds.",
      lingerOp.Enabled.ToString(),
      lingerOp.LingerTime.ToString());

    Console.WriteLine(
      "Size of the receive buffer is now {0} bytes.",
      receiveBuffer.ToString());
  }
}
   
The output is

Linger option is False and set to 0 seconds.

Size of the receive buffer is 8192 bytes.

The SetSocketOption method has been called.

Linger option is now True and set to 10 seconds.

Size of the receive buffer is now 2048 bytes.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, byte[]) Method

public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue);

Summary

Retrieves the value of the specified socket option.

Parameters

optionLevel
One of the values defined in the SocketOptionLevel enumeration.
optionName
One of the values defined in the SocketOptionName enumeration.
optionValue
A Byte array that receives the value of the specified socket option.

Exceptions

Exception TypeCondition
SocketExceptionoptionValue is too small to store the value of the specified socket option.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

Socket options determine the behavior of the current instance.

Upon successful completion, the array specified by the optionValue parameter contains the value of the specified socket option.

When the length of the optionValue array is smaller than the number of bytes required to store the value of the specified socket option, a SocketException exception is thrown.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.GetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, int) Method

public byte[] GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength);

Summary

Retrieves the value of the specified socket option.

Parameters

optionLevel
One of the values defined in the SocketOptionLevel enumeration.
optionName
One of the values defined in the SocketOptionName enumeration.
optionLength
A Int32 containing the maximum length, in bytes, of the value of the specified socket option.

Return Value

A Byte array containing the value of the specified socket option.

Exceptions

Exception TypeCondition
SocketExceptionoptionLength is smaller than the number of bytes required to store the value of the specified socket option.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

Socket options determine the behavior of the current instance.

The optionLength parameter is used to allocate an array to store the value of the specified option. When this value is smaller than the number of bytes required to store the value of the specified option, a SocketException exception is thrown. When this value is greater than or equal to the number of bytes required to store the value of the specified option, the array returned by this method is allocated to be exactly the required length.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.IOControl Method

public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue);

Summary

Provides low-level access to the socket, the transport protocol, or the communications subsystem.

Parameters

ioControlCode
A Int32 containing the control code of the operation to perform.
optionInValue
A Byte array containing the input data required by the operation.
optionOutValue
A Byte array containing the output data supplied by the operation.

Return Value

A Int32 containing the length of the optionOutValue array after the method returns.

Exceptions

Exception TypeCondition
InvalidOperationExceptionAn attempt was made to change the blocking mode.

[Note: Use the System.Net.Sockets.Socket.Blocking property to change the blocking mode.

]

SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.
SecurityExceptionA caller in the call stack does not have the required permissions.

Description

If an attempt is made to change the blocking mode of the current instance, an exception is thrown. Use the System.Net.Sockets.Socket.Blocking property to change the blocking mode.

The control codes and their requirements are implementation defined. Do not use this method if platform independence is a requirement.

[Note: Input data is not required for all control codes. Output data is not supplied by all control codes and, if not supplied, the return value is 0. ]

Example

The following example gets the number of bytes of available data to be read and writes the result to the console on a Windows system. The remote endpoint (remoteEndpoint) to connect to might need to be changed to a value that is valid on the current system.

using System;
using System.Net;
using System.Net.Sockets;

class App {

  static void Main() {

    IPAddress remoteAddress =
    Dns.Resolve(Dns.GetHostName()).AddressList[0];

    IPEndPoint remoteEndpoint =
      new IPEndPoint(remoteAddress, 80);

    Socket someSocket =
      new Socket(AddressFamily.InterNetwork,
                 SocketType.Stream,
                 ProtocolType.Tcp);

    someSocket.Connect(remoteEndpoint);

    int fionRead = 0x4004667F;
    byte[]inValue = {0x00, 0x00, 0x00, 0x00};
    byte[]outValue = {0x00, 0x00, 0x00, 0x00};

    someSocket.IOControl(fionRead, inValue, outValue);

    uint bytesAvail = BitConverter.ToUInt32(outValue, 0);
      
    Console.WriteLine(
      "There are {0} bytes available to be read.",
      bytesAvail.ToString() );
  }
}
      
The output is

There are 0 bytes available to be read.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Listen Method

public void Listen(int backlog);

Summary

Places the current instance into the listening state where it waits for incoming connection requests.

Parameters

backlog
A Int32 containing the maximum length of the queue of pending connections.

Exceptions

Exception TypeCondition
SocketExceptionThe System.Net.Sockets.Socket.Connected property of the current instance is true.-or-

Bind has not been called on the current instance.-or-

An error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

Once this method is called, incoming connection requests are placed in a queue. The maximum size of the queue is specified by the backlog parameter. The size of the queue is limited to legal values by the underlying protocol. Illegal values of the backlog parameter are replaced with a legal value, which is implementation defined.

If a connection request arrives and the queue is full, a SocketException is thrown on the client.

A socket in the listening state has no remote endpoint associated with it. Attempting to access the System.Net.Sockets.Socket.RemoteEndPoint property throws a SocketException exception.

This method is ignored if called more than once on the current instance.

[Note: This method is used only on the server-side of connection-oriented protocols. Call the System.Net.Sockets.Socket.Bind(System.Net.EndPoint) method before this method is called the first time. Call the System.Net.Sockets.Socket.Listen(System.Int32) method before the first call to the System.Net.Sockets.Socket.Accept method.

]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Poll Method

public bool Poll(int microSeconds, SelectMode mode);

Summary

Determines the read, write, or error status of the current instance.

Parameters

microSeconds
A Int32 containing the time to wait for a response, in microseconds. Set the microSeconds parameter to a negative value to wait indefinitely for a response.
mode
One of the values defined in the SelectMode enumeration.

Return Value

A Boolean where true indicates the current instance satisfies at least one of the conditions in the following table corresponding to the specified SelectMode value; otherwise, false . false is returned if the status of the current instance cannot be determined within the time specified by microSeconds .

SelectMode value Condition
SelectRead Data is available for reading (includes out-of-band data if the System.Net.Sockets.SocketOptionName.OutOfBandInline value defined in the SocketOptionName enumeration is set).

-or-

The socket is in the listening state with a pending connection, and the System.Net.Sockets.Socket.Accept method has been called and is guaranteed to succeed without blocking.

-or-

The connection has been closed, reset, or terminated.

SelectWriteData can be sent.

-or-

A non-blocking System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method is being processed and the connection has succeeded.

SelectErrorThe System.Net.Sockets.SocketOptionName.OutOfBandInline value defined in the SocketOptionName enumeration is not set and out-of-band data is available.

-or-

A non-blocking System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method is being processed and the connection has failed.

Exceptions

Exception TypeCondition
NotSupportedExceptionmode is not one of the values defined in the SelectMode enumeration.
SocketExceptionAn error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Receive(byte[], int, System.Net.Sockets.SocketFlags) Method

public int Receive(byte[] buffer, int size, SocketFlags socketFlags);

Summary

Receives data from a socket.

Parameters

buffer
A Byte array to store data received from the socket.
size
A Int32 containing the number of bytes to receive.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionsize < 0.

-or-

size > buffer.Length.

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, size, socketFlags).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Receive(byte[], System.Net.Sockets.SocketFlags) Method

public int Receive(byte[] buffer, SocketFlags socketFlags);

Summary

Receives data from a socket.

Parameters

buffer
A Byte array to store data received from the socket.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityException A caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, socketFlags).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Receive(byte[], int, int, System.Net.Sockets.SocketFlags) Method

public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags);

Summary

Receives data from a socket.

Parameters

buffer
A Byte array to store data received from the socket.
offset
A Int32 containing the zero-based position in buffer to begin storing the received data.
size
A Int32 containing the number of bytes to receive.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionoffset < 0.

-or-

offset > buffer.Length.

-or-

size < 0.

-or-

size > buffer.Length - offset.

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

The System.Net.Sockets.Socket.LocalEndPoint property was not set.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

The System.Net.Sockets.Socket.LocalEndPoint property is required to be set before this method is called.

The System.Net.Sockets.Socket.Blocking property of the socket determines the behavior of this method when no incoming data is available. When false , the SocketException exception is thrown. When true , this method blocks and waits for data to arrive.

For System.Net.Sockets.SocketType.Stream socket types, if the remote socket was shut down gracefully, and all data was received, this method immediately returns zero, regardless of the blocking state.

For message-oriented sockets, if the message is larger than the size of buffer, the buffer is filled with the first part of the message, and the SocketException exception is thrown. For unreliable protocols, the excess data is lost; for reliable protocols, the data is retained by the service provider.

When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of the socketFlags parameter and the socket is configured for in-line reception of out-of-band (OOB) data (using the System.Net.Sockets.SocketOptionName.OutOfBandInline socket option) and OOB data is available, only OOB data is returned.

When the System.Net.Sockets.SocketFlags.Peek flag is specified as part of the socketFlags parameter, available data is copied into buffer but is not removed from the system buffer.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Receive(byte[]) Method

public int Receive(byte[] buffer);

Summary

Receives data from a socket.

Parameters

buffer
A Byte array to store data received from the socket.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionAn error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityException A caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.ReceiveFrom(byte[], System.Net.EndPoint&) Method

public int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP);

Summary

Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data.

Parameters

buffer
A Byte array to store data received from the socket.
remoteEP
A reference to the EndPoint associated with the socket that sent the data.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer or remoteEP is null .

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, remoteEP).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.ReceiveFrom(byte[], System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method

public int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP);

Summary

Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data.

Parameters

buffer
A Byte array to store data received from the socket.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
remoteEP
A reference to the EndPoint associated with the socket that sent the data.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer or remoteEP is null .

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags specified an invalid value.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@)(buffer, 0, buffer.Length, socketFlags, remoteEP).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.ReceiveFrom(byte[], int, System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method

public int ReceiveFrom(byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP);

Summary

Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data.

Parameters

buffer
A Byte array to store data received from the socket.
size
A Int32 containing the number of bytes to receive.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
remoteEP
A reference to the EndPoint associated with the socket that sent the data.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer or remoteEP is null .

ArgumentOutOfRangeExceptionsize < 0.

-or-

size > buffer.Length.

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@)(buffer, 0, size , socketFlags, remoteEP ).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.ReceiveFrom(byte[], int, int, System.Net.Sockets.SocketFlags, System.Net.EndPoint&) Method

public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP);

Summary

Receives data from a socket and, for connectionless protocols, stores the endpoint associated with the socket that sent the data.

Parameters

buffer
A Byte array to store data received from the socket.
offset
A Int32 containing the zero-based position in buffer to begin storing the received data.
size
A Int32 containing the number of bytes to receive.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.OutOfBand, or System.Net.Sockets.SocketFlags.Peek.
remoteEP
A reference to the EndPoint associated with the socket that sent the data.

Return Value

A Int32 containing the number of bytes received.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer or remoteEP is null .

ArgumentOutOfRangeExceptionoffset < 0.

-or-

offset > buffer.Length.

-or-

size < 0.

-or-

size > buffer.Length - offset.

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

The System.Net.Sockets.Socket.LocalEndPoint property was not set.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

For connectionless protocols, when this method successfully completes, remoteEP contains the endpoint associated with the socket that sent the data.

For connection-oriented protocols, remoteEP is left unchanged.

The System.Net.Sockets.Socket.LocalEndPoint property is required to be set before this method is called or a SocketException is thrown.

The System.Net.Sockets.Socket.Blocking property of the socket determines the behavior of this method when no incoming data is available. When false , the SocketException exception is thrown. When true , this method blocks and waits for data to arrive.

For System.Net.Sockets.SocketType.Stream socket types, if the remote socket was shut down gracefully, and all data was received, this method immediately returns zero, regardless of the blocking state.

For message-oriented sockets, if the message is larger than the size of buffer, the buffer is filled with the first part of the message, and the SocketException exception is thrown. For unreliable protocols, the excess data is lost; for reliable protocols, the data is retained by the service provider.

When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of thesocketFlags parameter and the socket is configured for in-line reception of out-of-band (OOB) data (using the System.Net.Sockets.SocketOptionName.OutOfBandInline socket option) and OOB data is available, only OOB data is returned.

When the System.Net.Sockets.SocketFlags.Peek flag is specified as part of the socketFlags parameter, available data is copied into buffer but is not removed from the system buffer.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Select Method

public static void Select(IList checkRead, IList checkWrite, IList checkError, int microSeconds);

Summary

Determines the read, write, or error status of a set of Socket instances.

Parameters

checkRead
A IList object containing the Socket instances to check for read status.
checkWrite
A IList object containing the Socket instances to check for write status.
checkError
A IList object containing the Socket instances to check for error status.
microSeconds
A Int32 that specifies the time to wait for a response, in microseconds. Specify a negative value to wait indefinitely for the status to be determined.

Exceptions

Exception TypeCondition
ArgumentNullExceptionAll of the following parameters are null or empty: checkRead, checkWrite, and checkError.
SocketExceptionAn error occurred while accessing one of the sockets. [Note: For additional information on causes of the SocketException , see the SocketException class.]

Description

Upon successful completion, this method removes all Socket instances from the specified list that do not satisfy one of the conditions associated with that list. The following table describes the conditions for each list.

ListCondition to remain in list
checkReadData is available for reading (includes out-of-band data if the System.Net.Sockets.SocketOptionName.OutOfBandInline value defined in the SocketOptionName enumeration is set).

-or-

The socket is in the listening state with a pending connection, and the System.Net.Sockets.Socket.Accept method has been called and is guaranteed to succeed without blocking.

-or-

The connection has been closed, reset, or terminated.

checkWriteData can be sent.

-or-

A non-blocking System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method is being processed and the connection has succeeded.

checkErrorThe System.Net.Sockets.SocketOptionName.OutOfBandInline value defined in the SocketOptionName enumeration is not set and out-of-band data is available.

-or-

A non-blocking System.Net.Sockets.Socket.Connect(System.Net.EndPoint) method is being processed and the connection has failed.

[Note: To determine the status of a specific Socket instance, check whether the instance remains in the list after the method returns.]

When the method cannot determine the status of all the Socket instances within the time specified in the microseconds parameter, the method removes all the Socket instances from all the lists and returns.

At least one of checkRead, checkWrite, or checkError, is required to contain at least one Socket instance. The other parameters can be empty or null .

Example

The following example determines the status of the socket instance named socket3 and writes the result to the console.

using System;
using System.Collections;
using System.Net.Sockets;

class SelectTest {

  public static void Main() {

    Socket socket1 =
      new Socket(AddressFamily.InterNetwork,
                 SocketType.Stream,
                 ProtocolType.Tcp);
    Socket socket2 =
      new Socket(AddressFamily.InterNetwork,
                 SocketType.Stream,
                 ProtocolType.Tcp);
    Socket socket3 =
      new Socket(AddressFamily.InterNetwork,
                 SocketType.Stream,
                 ProtocolType.Tcp);

    ArrayList readList = new ArrayList();
    ArrayList writeList = new ArrayList();
    ArrayList errorList = new ArrayList();

    readList.Add(socket1);
    readList.Add(socket2);
    readList.Add(socket3);
    errorList.Add(socket1);
    errorList.Add(socket3);

    // readList.Contains(Socket3) returns true
    // if Socket3 is in ReadList.
    Console.WriteLine(
      "socket3 is placed in readList and errorList.");
    Console.WriteLine(
      "socket3 is {0}in readList.",
      readList.Contains(socket3) ? "" : "not " );
    Console.WriteLine(
      "socket3 is {0}in writeList.",
      writeList.Contains(socket3) ? "" : "not " );
    Console.WriteLine(
      "socket3 is {0}in errorList.",
      errorList.Contains(socket3) ? "" : "not " );

    Socket.Select(readList, writeList, errorList, 10);
    Console.WriteLine("The Select method has been called.");
    Console.WriteLine(
      "socket3 is {0}in readList.",
      readList.Contains(socket3) ? "" : "not " );
    Console.WriteLine(
      "socket3 is {0}in writeList.",
      writeList.Contains(socket3) ? "" : "not " );
    Console.WriteLine(
      "socket3 is {0}in errorList.",
      errorList.Contains(socket3) ? "" : "not " );
  }
}
   
The output is

socket3 is placed in readList and errorList.

socket3 is in readList.

socket3 is not in writeList.

socket3 is in errorList.

The Select method has been called.

socket3 is not in readList.

socket3 is not in writeList.

socket3 is not in errorList.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Send(byte[], int, int, System.Net.Sockets.SocketFlags) Method

public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags);

Summary

Sends data to a connected socket.

Parameters

buffer
A Byte array containing data to send to the socket.
offset
A Int32 that specifies the zero-based position in buffer that is the starting location of the data to send.
size
A Int32 containing the number of bytes to send.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionoffset < 0.

-or-

offset > buffer.Length.

-or-

size < 0.

-or-

size > buffer.Length - offset.

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

For connection-oriented protocols, the System.Net.Sockets.Socket.LocalEndPoint property of the current instance is required to be set before calling this method.

For connectionless protocols, calling the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) methods sets the System.Net.Sockets.Socket.RemoteEndPoint property and allows the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method to be used instead of the System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) method.

When the System.Net.Sockets.SocketFlags.DontRoute flag is specified as part of the socketFlags parameter, the sent data is not routed.

When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of the socketFlags parameter, only out-of-band (OOB) data is sent.

When the System.Net.Sockets.Socket.Blocking property of the current instance is set to true and buffer space is not available within the underlying protocol, this method blocks.

For message-oriented sockets, when size is greater than the maximum message size of the underlying protocol, no data is sent and the SocketException exception is thrown.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Send(byte[]) Method

public int Send(byte[] buffer);

Summary

Sends data to a connected socket.

Parameters

buffer
A Byte array containing data to send to the socket.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionAn error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Send(byte[], System.Net.Sockets.SocketFlags) Method

public int Send(byte[] buffer, SocketFlags socketFlags);

Summary

Sends data to a connected socket.

Parameters

buffer
A Byte array containing data to send to the socket.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, buffer.Length, socketFlags).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Send(byte[], int, System.Net.Sockets.SocketFlags) Method

public int Send(byte[] buffer, int size, SocketFlags socketFlags);

Summary

Sends data to a connected socket.

Parameters

buffer
A Byte array containing data to send to the socket.
size
A Int32 containing the number of bytes to send.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer is null .
ArgumentOutOfRangeExceptionsize < 0.

-or-

size > buffer.Length.

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags)(buffer, 0, size, socketFlags).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.SendTo(byte[], System.Net.EndPoint) Method

public int SendTo(byte[] buffer, EndPoint remoteEP);

Summary

Sends data to the socket associated with the specified endpoint.

Parameters

buffer
A Byte array containing data to send to the socket.
remoteEP
The EndPoint associated with the socket to receive the data.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer or remoteEP is null .

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint)(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, remoteEP).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.SendTo(byte[], System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method

public int SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP);

Summary

Sends data to the socket associated with the specified endpoint.

Parameters

buffer
A Byte array containing data to send to the socket.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.
remoteEP
The EndPoint associated with the socket to receive the data.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer or remoteEP is null .

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint)(buffer, 0, buffer.Length, socketFlags, remoteEP).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.SendTo(byte[], int, System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method

public int SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP);

Summary

Sends data to the socket associated with the specified endpoint.

Parameters

buffer
A Byte array containing data to send to the socket.
size
A Int32 containing the number of bytes to send.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.
remoteEP
The EndPoint associated with the socket to receive the data.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer or remoteEP is null .

ArgumentOutOfRangeExceptionsize < 0.

-or-

size > buffer.Length.

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

This method is equivalent to System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint)(buffer, 0, size, socketFlags, remoteEP).

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.SendTo(byte[], int, int, System.Net.Sockets.SocketFlags, System.Net.EndPoint) Method

public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP);

Summary

Sends data to the socket associated with the specified endpoint.

Parameters

buffer
A Byte array containing data to send to the socket.
offset
A Int32 that specifies the zero-based position in buffer that is the starting location of the data to send.
size
A Int32 containing the number of bytes to send.
socketFlags
A bitwise combination of any of the following values defined in the SocketFlags enumeration: System.Net.Sockets.SocketFlags.None, System.Net.Sockets.SocketFlags.DontRoute, or System.Net.Sockets.SocketFlags.OutOfBand.
remoteEP
The EndPoint associated with the socket to receive the data.

Return Value

A Int32 containing the number of bytes sent.

Exceptions

Exception TypeCondition
ArgumentNullExceptionbuffer or remoteEP is null .

ArgumentOutOfRangeExceptionoffset < 0.

-or-

offset > buffer.Length.

-or-

size < 0.

-or-

size > buffer.Length - offset.

InvalidOperationExceptionAn asynchronous call is pending and a blocking method has been called.

SocketExceptionsocketFlags is not a valid combination of values.

-or-

An error occurred while accessing the socket.

[Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityException A caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

For connected sockets using connectionless protocols, remoteEP overrides the endpoint specified in the System.Net.Sockets.Socket.RemoteEndPoint property.

For unconnected sockets using connectionless protocols, this method sets the System.Net.Sockets.Socket.LocalEndPoint property of the current instance to a value determined by the protocol. Subsequent data is required to be received on LocalEndPoint .

When the System.Net.Sockets.SocketFlags.DontRoute flag is specified as part of the socketFlags parameter, the sent data is not routed.

When the System.Net.Sockets.SocketFlags.OutOfBand flag is specified as part of the socketFlags parameter, only out-of-band (OOB) data is sent.

When the System.Net.Sockets.Socket.Blocking property of the current instance is set to true and buffer space is not available within the underlying protocol, this method blocks.

For message-oriented sockets, when size is greater than the maximum message size of the underlying protocol, no data is sent and the SocketException exception is thrown.

For connection-oriented sockets, the remoteEP parameter is ignored.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, System.Object) Method

public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue);

Summary

Sets the System.Net.Sockets.SocketOptionName.AddMembership, System.Net.Sockets.SocketOptionName.DropMembership, or System.Net.Sockets.SocketOptionName.Linger socket options.

Parameters

optionLevel
Either the Socket or IP member of the SocketOptionLevel enumeration.
optionName
Either the Linger , AddMembership , or DropMembership member of the SocketOptionName enumeration.
optionValue
An instance of the LingerOption or MulticastOption class.

Exceptions

Exception TypeCondition
ArgumentExceptionoptionLevel, optionName, or optionValue specified an invalid value.
ArgumentNullExceptionoptionValue is null .
SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

Socket options determine the behavior of the current instance. Multiple options can be set on the current instance by calling this method multiple times.

The following table summarizes the valid combinations of input parameters.

optionLevel/optionNameoptionValue
Socket /Linger An instance of the LingerOption class.
IP /AddMembership

- or -

IP /DropMembership

An instance of the MulticastOption class.
When setting the System.Net.Sockets.SocketOptionName.Linger option, a ArgumentException exception is thrown if the System.Net.Sockets.LingerOption.LingerTime property of the LingerOption instance is less than zero or greater than System.UInt16.MaxValue .

[Note: For more information on the System.Net.Sockets.SocketOptionName.Linger option, see the LingerOption class and the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method.

For more information on the System.Net.Sockets.SocketOptionName.AddMembership and System.Net.Sockets.SocketOptionName.DropMembership options, see the MulticastOption class.

For socket options with values of type Int32 or Boolean, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel, SocketOptionName, Int32) version of this method.

]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, byte[]) Method

public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue);

Summary

Sets socket options with values of type Byte[] .

Parameters

optionLevel
One of the values defined in the SocketOptionLevel enumeration.
optionName
One of the values defined in the SocketOptionName enumeration.
optionValue
A Byte array containing the value of the option.

Exceptions

Exception TypeCondition
SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

Socket options determine the behavior of the current instance. Multiple options can be set on the current instance by calling this method multiple times.

[Note: For socket options with values of type Int32 or Boolean, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel, SocketOptionName , Int32) version of this method.]

[Note: For the System.Net.Sockets.SocketOptionName.AddMembership, System.Net.Sockets.SocketOptionName.DropMembership, or System.Net.Sockets.SocketOptionName.Linger socket options, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel, SocketOptionName, Object) version of this method.]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel, System.Net.Sockets.SocketOptionName, int) Method

public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue);

Summary

Sets socket options with values of type Int32 and Boolean.

Parameters

optionLevel
One of the values defined in the SocketOptionLevel enumeration.
optionName
One of the values defined in the SocketOptionName enumeration.
optionValue
A Int32 containing the value of the option.

Exceptions

Exception TypeCondition
SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

SecurityExceptionA caller in the call stack does not have the required permissions.
ObjectDisposedExceptionThe current instance has been disposed.

Description

Socket options determine the behavior of the current instance. Multiple options can be set on the current instance by calling this method multiple times.

For a socket option with a Boolean data type, specify a non-zero optionValue to enable the option, and an optionValue equal to zero to disable the option.

Socket options are grouped by level of protocol support. The following tables list the members of the SocketOptionName enumeration supported by each member of the SocketOptionLevel enumeration. Only members that have associated values of the Int32 and Boolean data types are listed.

The following table lists the members of the SocketOptionName enumeration supported by the Socket member of the SocketOptionLevel enumeration. Options that do not require permission to access unmanaged code are noted.
SocketOptionNameDescription
BroadcastA Boolean where true indicates broadcast messages are allowed to be sent to the socket.
DebugA Boolean where true indicates to record debugging information.
DontLingerA Boolean where true indicates to close the socket without lingering. This option does not require permission to access unmanaged code.
DontRouteA Boolean where true indicates not to route data.
ErrorA Int32 that contains the error code associated with the last socket error. The error code is cleared by this option. This option is read-only.
KeepAliveA Boolean where true (the default) indicates to enable keep-alives, which allows a connection to remain open after a request has completed. This option does not require permission to access unmanaged code.
OutOfBandInlineA Boolean where true indicates to receive out-of-band data in the normal data stream.
ReceiveBufferA Int32 that specifies the total per-socket buffer space reserved for receives. This option does not require permission to access unmanaged code.
ReceiveTimeoutA Int32 that specifies the maximum time, in milliseconds, the System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) and System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@) methods will block when attempting to receive data. If data is not received within this time, a SocketException exception is thrown. This option does not require permission to access unmanaged code.
ReuseAddressA Boolean where true allows the socket to be bound to an address that is already in use.
SendBufferA Int32 that specifies the total per-socket buffer space reserved for sends. This option does not require permission to access unmanaged code.
SendTimeoutA Int32 that specifies the maximum time, in milliseconds, the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) and System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) methods will block when attempting to send data. If data is not sent within this time, a SocketException exception is thrown. This option does not require permission to access unmanaged code.
TypeOne of the values defined in the SocketType enumeration. This option is read-only.

The following table lists the members of the SocketOptionName enumeration supported by the IP member of the SocketOptionLevel enumeration. These options require permission to access unmanaged code.

SocketOptionNameDescription
HeaderIncludedA Boolean where true indicates the application is providing the IP header for outgoing datagrams.
IPOptionsA Byte array that specifies IP options to be inserted into outgoing datagrams.
IpTimeToLiveA Int32 that specifies the time-to-live for datagrams. The time-to-live designates the number of networks on which the datagram is allowed to travel before being discarded by a router.
MulticastInterfaceA Byte array that specifies the interface for outgoing multicast packets.
MulticastLoopbackA Boolean where true enables multicast loopback.
MulticastTimeToLiveA Int32 that specifies the time-to-live for multicast datagrams.
TypeOfServiceA Int32 that specifies the type of service field in the IP header.
UseLoopbackA Boolean where true indicates to send a copy of the data back to the sender.

The following table lists the members of the SocketOptionName enumeration supported by the Tcp member of the SocketOptionLevel enumeration. These options do not require permission to access unmanaged code.

SocketOptionNameDescription
BsdUrgentA Boolean where true indicates to use urgent data as defined by IETF RFC 1222. Once enabled, this option cannot be disabled.
ExpeditedA Boolean where true indicates to use expedited data as defined by IETF RFC 1222. Once enabled, this option cannot be disabled.
NoDelayA Boolean where true indicates to disable the Nagle algorithm for send coalescing.

The following table lists the members of the SocketOptionName enumeration supported by the Udp member of the SocketOptionLevel enumeration. These options do not require permission to access unmanaged code.

SocketOptionNameDescription
ChecksumCoverageA Boolean that specifies UDP checksum coverage.
NoChecksumA Boolean where true indicates to send UDP datagrams with the checksum set to zero.

[Note: For the AddMembership , DropMembership , and Linger members of the SocketOptionName enumeration, see the System.Net.Sockets.Socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel,System.Net.Sockets.SocketOptionName,System.Int32)(SocketOptionLevel, SocketOptionName, Object) version of this method.

]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Shutdown Method

public void Shutdown(SocketShutdown how);

Summary

Terminates the ability to send or receive data on a connected socket.

Parameters

how
One of the values defined in the SocketShutdown enumeration.

Exceptions

Exception TypeCondition
SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

When how is set to System.Net.Sockets.SocketShutdown.Send , the socket on the other end of the connection is notified that the current instance will not send any more data. If the System.Net.Sockets.Socket.Send(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method is subsequently called, a SocketException exception is thrown.

When how is set to System.Net.Sockets.SocketShutdown.Receive, the socket on the other end of the connection is notified that the current instance will not receive any more data. After all the data currently queued on the current instance is received, any subsequent calls to the System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) method cause a SocketException exception to be thrown.

Setting how to System.Net.Sockets.SocketShutdown.Both terminates both sends and receives as described above. Once this occurs, the socket cannot be used.

[Note: To free resources allocated by the current instance, call the System.Net.Sockets.Socket.Close method.

Expected common usage is for the System.Net.Sockets.Socket.Shutdown(System.Net.Sockets.SocketShutdown) method to be called before the System.Net.Sockets.Socket.Close method to ensure that all pending data is sent or received.

]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.System.IDisposable.Dispose Method

void IDisposable.Dispose();

Summary

Implemented to support the IDisposable interface. [Note: For more information, see System.IDisposable.Dispose.]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.AddressFamily Property

public AddressFamily AddressFamily { get; }

Summary

Gets the address family of the current instance.

Property Value

One of the values defined in the AddressFamily enumeration.

Description

This property is read-only.

This property is set by the constructor for the current instance. The value of this property specifies the addressing scheme used by the current instance to resolve an address.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Available Property

public int Available { get; }

Summary

Gets the amount of data available to be read in a single System.Net.Sockets.Socket.Receive(System.Byte[],System.Int32,System.Net.Sockets.SocketFlags) or System.Net.Sockets.Socket.ReceiveFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@) call.

Property Value

A Int32 containing the number of bytes of data that are available to be read.

Exceptions

Exception TypeCondition
SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This property is read-only.

When the current instance is stream-oriented (for example, the System.Net.Sockets.SocketType.Stream socket type), the available data is generally the total amount of data queued on the current instance.

When the current instance is message-oriented (for example, the System.Net.Sockets.SocketType.Dgram socket type), the available data is the first message in the input queue.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Blocking Property

public bool Blocking { get; set; }

Summary

Gets or sets a Boolean value that indicates whether the socket is in blocking mode.

Property Value

true indicates that the current instance is in blocking mode; false indicates that the current instance is in non-blocking mode.

Exceptions

Exception TypeCondition
ObjectDisposedExceptionThe current instance has been disposed.

Description

Blocking is when a method waits to complete an operation before returning. Sockets are created in blocking mode by default.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Connected Property

public bool Connected { get; }

Summary

Gets a Boolean value indicating whether the current instance is connected.

Property Value

true indicates that the current instance was connected at the time of the last I/O operation; false indicates that the current instance is not connected.

Description

This property is read-only.

When this property returns true , the current instance was connected at the time of the last I/O operation; it might not still be connected. When this property returns false , the current instance was never connected or is not currently connected.

The current instance is considered connected when the System.Net.Sockets.Socket.RemoteEndPoint property contains a valid endpoint.

[Note: The System.Net.Sockets.Socket.Accept and System.Net.Sockets.Socket.Connect(System.Net.EndPoint) methods, and their asynchronous counterparts set this property.]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.Handle Property

public IntPtr Handle { get; }

Summary

Gets the operating system handle for the current instance.

Property Value

A IntPtr containing the operating system handle for the current instance.

Description

This property is read-only.

Library

RuntimeInfrastructure

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.LocalEndPoint Property

public EndPoint LocalEndPoint { get; }

Summary

Gets the local endpoint associated with the current instance.

Property Value

The local EndPoint associated with the current instance.

Exceptions

Exception TypeCondition
SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This property is read-only.

This property contains the network connection information for the current instance.

[Note: The System.Net.Sockets.Socket.Bind(System.Net.EndPoint) and System.Net.Sockets.Socket.Accept methods, and their asynchronous counterparts set this property. If not previously set, the System.Net.Sockets.Socket.Connect(System.Net.EndPoint) and System.Net.Sockets.Socket.SendTo(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint) methods, and their asynchronous counterparts set this property. ]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.ProtocolType Property

public ProtocolType ProtocolType { get; }

Summary

Gets the protocol type of the current instance.

Property Value

One of the values defined in the ProtocolType enumeration.

Description

This property is read-only.

This property is set by the constructor for the current instance. The value of this property specifies the protocol used by the current instance.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.RemoteEndPoint Property

public EndPoint RemoteEndPoint { get; }

Summary

Gets the remote endpoint associated with the current instance.

Property Value

The remote EndPoint associated with the current instance.

Exceptions

Exception TypeCondition
SocketExceptionAn error occurred while accessing the socket. [Note: For additional information on causes of the SocketException , see the SocketException class.]

ObjectDisposedExceptionThe current instance has been disposed.

Description

This property is read-only.

This property contains the network connection information associated with the socket communicating with the current instance.

There is no remote endpoint associated with a socket in the listening state. An attempt to access the System.Net.Sockets.Socket.RemoteEndPoint property causes a SocketException exception to be thrown.

[Note: The System.Net.Sockets.Socket.Accept and System.Net.Sockets.Socket.Connect(System.Net.EndPoint) methods, and their asynchronous counterparts set this property. ]

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace

Socket.SocketType Property

public SocketType SocketType { get; }

Summary

Gets the socket type of the current instance.

Property Value

One of the values defined in the SocketType enumeration.

Description

This property is read-only.

This property is set by the constructor for the current instance.

See Also

System.Net.Sockets.Socket Class, System.Net.Sockets Namespace