Export (0) Print
Expand All

Socket Class

Implements the Berkeley sockets interface.

System::Object
  System.Net.Sockets::Socket

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)

public ref class Socket : IDisposable

The Socket type exposes the following members.

  NameDescription
Public methodSocket(SocketInformation)Initializes a new instance of the Socket class using the specified value returned from DuplicateAndClose.
Public methodSocket(SocketType, ProtocolType)Initializes a new instance of the Socket class using the specified socket type and protocol.
Public methodSocket(AddressFamily, SocketType, ProtocolType)Initializes a new instance of the Socket class using the specified address family, socket type and protocol.
Top

  NameDescription
Public propertyAddressFamilyGets the address family of the Socket.
Public propertyAvailableGets the amount of data that has been received from the network and is available to be read.
Public propertyBlockingGets or sets a value that indicates whether the Socket is in blocking mode.
Public propertyConnectedGets a value that indicates whether a Socket is connected to a remote host as of the last Send or Receive operation.
Public propertyDontFragmentGets or sets a Boolean value that specifies whether the Socket allows Internet Protocol (IP) datagrams to be fragmented.
Public propertyDualModeGets or sets a Boolean value that specifies whether the Socket is a dual-mode socket used for both IPv4 and IPv6.
Public propertyEnableBroadcastGets or sets a Boolean value that specifies whether the Socket can send or receive broadcast packets.
Public propertyExclusiveAddressUseGets or sets a Boolean value that specifies whether the Socket allows only one process to bind to a port.
Public propertyHandleGets the operating system handle for the Socket.
Public propertyIsBoundGets a value that indicates whether the Socket is bound to a specific local port.
Public propertyLingerStateGets or sets a value that specifies whether the Socket will delay closing a socket in an attempt to send all pending data.
Public propertyLocalEndPointGets the local endpoint.
Public propertyMulticastLoopbackGets or sets a value that specifies whether outgoing multicast packets are delivered to the sending application.
Public propertyNoDelayGets or sets a Boolean value that specifies whether the stream Socket is using the Nagle algorithm.
Public propertyStatic memberOSSupportsIPv4Indicates whether the underlying operating system and network adaptors support Internet Protocol version 4 (IPv4).
Public propertyStatic memberOSSupportsIPv6Indicates whether the underlying operating system and network adaptors support Internet Protocol version 6 (IPv6).
Public propertyProtocolTypeGets the protocol type of the Socket.
Public propertyReceiveBufferSizeGets or sets a value that specifies the size of the receive buffer of the Socket.
Public propertyReceiveTimeoutGets or sets a value that specifies the amount of time after which a synchronous Receive call will time out.
Public propertyRemoteEndPointGets the remote endpoint.
Public propertySendBufferSizeGets or sets a value that specifies the size of the send buffer of the Socket.
Public propertySendTimeoutGets or sets a value that specifies the amount of time after which a synchronous Send call will time out.
Public propertySocketTypeGets the type of the Socket.
Public propertyStatic memberSupportsIPv4 Obsolete. Gets a value indicating whether IPv4 support is available and enabled on the current host.
Public propertyStatic memberSupportsIPv6 Obsolete. Gets a value that indicates whether the Framework supports IPv6 for certain obsolete Dns members.
Public propertyTtlGets or sets a value that specifies the Time To Live (TTL) value of Internet Protocol (IP) packets sent by the Socket.
Public propertyUseOnlyOverlappedIOSpecifies whether the socket should only use Overlapped I/O mode.
Top

  NameDescription
Public methodAcceptCreates a new Socket for a newly created connection.
Public methodAcceptAsyncBegins an asynchronous operation to accept an incoming connection attempt.
Public methodBeginAccept(AsyncCallback, Object)Begins an asynchronous operation to accept an incoming connection attempt.
Public methodBeginAccept(Int32, AsyncCallback, Object)Begins an asynchronous operation to accept an incoming connection attempt and receives the first block of data sent by the client application.
Public methodBeginAccept(Socket, Int32, AsyncCallback, Object)Begins an asynchronous operation to accept an incoming connection attempt from a specified socket and receives the first block of data sent by the client application.
Public methodBeginConnect(EndPoint, AsyncCallback, Object)Begins an asynchronous request for a remote host connection.
Public methodBeginConnect(IPAddress, Int32, AsyncCallback, Object)Begins an asynchronous request for a remote host connection. The host is specified by an IPAddress and a port number.
Public methodBeginConnect(array<IPAddress>, Int32, AsyncCallback, Object)Begins an asynchronous request for a remote host connection. The host is specified by an IPAddress array and a port number.
Public methodBeginConnect(String, Int32, AsyncCallback, Object)Begins an asynchronous request for a remote host connection. The host is specified by a host name and a port number.
Public methodBeginDisconnectBegins an asynchronous request to disconnect from a remote endpoint.
Public methodBeginReceive(IList<ArraySegment<Byte>>, SocketFlags, AsyncCallback, Object)Begins to asynchronously receive data from a connected Socket.
Public methodBeginReceive(IList<ArraySegment<Byte>>, SocketFlags, SocketError%, AsyncCallback, Object)Begins to asynchronously receive data from a connected Socket.
Public methodBeginReceive(array<Byte>, Int32, Int32, SocketFlags, AsyncCallback, Object)Begins to asynchronously receive data from a connected Socket.
Public methodBeginReceive(array<Byte>, Int32, Int32, SocketFlags, SocketError%, AsyncCallback, Object)Begins to asynchronously receive data from a connected Socket.
Public methodBeginReceiveFromBegins to asynchronously receive data from a specified network device.
Public methodBeginReceiveMessageFromBegins to asynchronously receive the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint and packet information..
Public methodBeginSend(IList<ArraySegment<Byte>>, SocketFlags, AsyncCallback, Object)Sends data asynchronously to a connected Socket.
Public methodBeginSend(IList<ArraySegment<Byte>>, SocketFlags, SocketError%, AsyncCallback, Object)Sends data asynchronously to a connected Socket.
Public methodBeginSend(array<Byte>, Int32, Int32, SocketFlags, AsyncCallback, Object)Sends data asynchronously to a connected Socket.
Public methodBeginSend(array<Byte>, Int32, Int32, SocketFlags, SocketError%, AsyncCallback, Object)Sends data asynchronously to a connected Socket.
Public methodBeginSendFile(String, AsyncCallback, Object)Sends the file fileName to a connected Socket object using the UseDefaultWorkerThread flag.
Public methodBeginSendFile(String, array<Byte>, array<Byte>, TransmitFileOptions, AsyncCallback, Object)Sends a file and buffers of data asynchronously to a connected Socket object.
Public methodBeginSendToSends data asynchronously to a specific remote host.
Public methodBindAssociates a Socket with a local endpoint.
Public methodStatic memberCancelConnectAsyncCancels an asynchronous request for a remote host connection.
Public methodClose()Closes the Socket connection and releases all associated resources.
Public methodClose(Int32)Closes the Socket connection and releases all associated resources with a specified timeout to allow queued data to be sent.
Public methodConnect(EndPoint)Establishes a connection to a remote host.
Public methodConnect(IPAddress, Int32)Establishes a connection to a remote host. The host is specified by an IP address and a port number.
Public methodConnect(array<IPAddress>, Int32)Establishes a connection to a remote host. The host is specified by an array of IP addresses and a port number.
Public methodConnect(String, Int32)Establishes a connection to a remote host. The host is specified by a host name and a port number.
Public methodConnectAsync(SocketAsyncEventArgs)Begins an asynchronous request for a connection to a remote host.
Public methodStatic memberConnectAsync(SocketType, ProtocolType, SocketAsyncEventArgs)Begins an asynchronous request for a connection to a remote host.
Public methodDisconnectCloses the socket connection and allows reuse of the socket.
Public methodDisconnectAsyncBegins an asynchronous request to disconnect from a remote endpoint.
Public methodDispose()Releases all resources used by the current instance of the Socket class.
Protected methodDispose(Boolean)Releases the unmanaged resources used by the Socket, and optionally disposes of the managed resources.
Public methodDuplicateAndCloseDuplicates the socket reference for the target process, and closes the socket for this process.
Public methodEndAccept(IAsyncResult)Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.
Public methodEndAccept(array<Byte>%, IAsyncResult)Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. This method returns a buffer that contains the initial data transferred.
Public methodEndAccept(array<Byte>%, Int32%, IAsyncResult)Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. This method returns a buffer that contains the initial data and the number of bytes transferred.
Public methodEndConnectEnds a pending asynchronous connection request.
Public methodEndDisconnectEnds a pending asynchronous disconnect request.
Public methodEndReceive(IAsyncResult)Ends a pending asynchronous read.
Public methodEndReceive(IAsyncResult, SocketError%)Ends a pending asynchronous read.
Public methodEndReceiveFromEnds a pending asynchronous read from a specific endpoint.
Public methodEndReceiveMessageFromEnds a pending asynchronous read from a specific endpoint. This method also reveals more information about the packet than EndReceiveFrom.
Public methodEndSend(IAsyncResult)Ends a pending asynchronous send.
Public methodEndSend(IAsyncResult, SocketError%)Ends a pending asynchronous send.
Public methodEndSendFileEnds a pending asynchronous send of a file.
Public methodEndSendToEnds a pending asynchronous send to a specific location.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeFrees resources used by the Socket class. (Overrides Object::Finalize().)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetSocketOption(SocketOptionLevel, SocketOptionName)Returns the value of a specified Socket option, represented as an object.
Public methodGetSocketOption(SocketOptionLevel, SocketOptionName, array<Byte>)Returns the specified Socket option setting, represented as a byte array.
Public methodGetSocketOption(SocketOptionLevel, SocketOptionName, Int32)Returns the value of the specified Socket option in an array.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIOControl(Int32, array<Byte>, array<Byte>)Sets low-level operating modes for the Socket using numerical control codes.
Public methodIOControl(IOControlCode, array<Byte>, array<Byte>)Sets low-level operating modes for the Socket using the IOControlCode enumeration to specify control codes.
Public methodListenPlaces a Socket in a listening state.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodPollDetermines the status of the Socket.
Public methodReceive(IList<ArraySegment<Byte>>)Receives data from a bound Socket into the list of receive buffers.
Public methodReceive(array<Byte>)Receives data from a bound Socket into a receive buffer.
Public methodReceive(IList<ArraySegment<Byte>>, SocketFlags)Receives data from a bound Socket into the list of receive buffers, using the specified SocketFlags.
Public methodReceive(array<Byte>, SocketFlags)Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.
Public methodReceive(IList<ArraySegment<Byte>>, SocketFlags, SocketError%)Receives data from a bound Socket into the list of receive buffers, using the specified SocketFlags.
Public methodReceive(array<Byte>, Int32, SocketFlags)Receives the specified number of bytes of data from a bound Socket into a receive buffer, using the specified SocketFlags.
Public methodReceive(array<Byte>, Int32, Int32, SocketFlags)Receives the specified number of bytes from a bound Socket into the specified offset position of the receive buffer, using the specified SocketFlags.
Public methodReceive(array<Byte>, Int32, Int32, SocketFlags, SocketError%)Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.
Public methodReceiveAsyncBegins an asynchronous request to receive data from a connected Socket object.
Public methodReceiveFrom(array<Byte>, EndPoint%)Receives a datagram into the data buffer and stores the endpoint.
Public methodReceiveFrom(array<Byte>, SocketFlags, EndPoint%)Receives a datagram into the data buffer, using the specified SocketFlags, and stores the endpoint.
Public methodReceiveFrom(array<Byte>, Int32, SocketFlags, EndPoint%)Receives the specified number of bytes into the data buffer, using the specified SocketFlags, and stores the endpoint.
Public methodReceiveFrom(array<Byte>, Int32, Int32, SocketFlags, EndPoint%)Receives the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint.
Public methodReceiveFromAsyncBegins to asynchronously receive data from a specified network device.
Public methodReceiveMessageFromReceives the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint and packet information.
Public methodReceiveMessageFromAsyncBegins to asynchronously receive the specified number of bytes of data into the specified location in the data buffer, using the specified SocketAsyncEventArgs::SocketFlags, and stores the endpoint and packet information.
Public methodStatic memberSelectDetermines the status of one or more sockets.
Public methodSend(IList<ArraySegment<Byte>>)Sends the set of buffers in the list to a connected Socket.
Public methodSend(array<Byte>)Sends data to a connected Socket.
Public methodSend(IList<ArraySegment<Byte>>, SocketFlags)Sends the set of buffers in the list to a connected Socket, using the specified SocketFlags.
Public methodSend(array<Byte>, SocketFlags)Sends data to a connected Socket using the specified SocketFlags.
Public methodSend(IList<ArraySegment<Byte>>, SocketFlags, SocketError%)Sends the set of buffers in the list to a connected Socket, using the specified SocketFlags.
Public methodSend(array<Byte>, Int32, SocketFlags)Sends the specified number of bytes of data to a connected Socket, using the specified SocketFlags.
Public methodSend(array<Byte>, Int32, Int32, SocketFlags)Sends the specified number of bytes of data to a connected Socket, starting at the specified offset, and using the specified SocketFlags.
Public methodSend(array<Byte>, Int32, Int32, SocketFlags, SocketError%)Sends the specified number of bytes of data to a connected Socket, starting at the specified offset, and using the specified SocketFlags
Public methodSendAsyncSends data asynchronously to a connected Socket object.
Public methodSendFile(String)Sends the file fileName to a connected Socket object with the UseDefaultWorkerThread transmit flag.
Public methodSendFile(String, array<Byte>, array<Byte>, TransmitFileOptions)Sends the file fileName and buffers of data to a connected Socket object using the specified TransmitFileOptions value.
Public methodSendPacketsAsyncSends a collection of files or in memory data buffers asynchronously to a connected Socket object.
Public methodSendTo(array<Byte>, EndPoint)Sends data to the specified endpoint.
Public methodSendTo(array<Byte>, SocketFlags, EndPoint)Sends data to a specific endpoint using the specified SocketFlags.
Public methodSendTo(array<Byte>, Int32, SocketFlags, EndPoint)Sends the specified number of bytes of data to the specified endpoint using the specified SocketFlags.
Public methodSendTo(array<Byte>, Int32, Int32, SocketFlags, EndPoint)Sends the specified number of bytes of data to the specified endpoint, starting at the specified location in the buffer, and using the specified SocketFlags.
Public methodSendToAsyncSends data asynchronously to a specific remote host.
Public methodSetIPProtectionLevelSet the IP protection level on a socket.
Public methodSetSocketOption(SocketOptionLevel, SocketOptionName, Boolean)Sets the specified Socket option to the specified Boolean value.
Public methodSetSocketOption(SocketOptionLevel, SocketOptionName, array<Byte>)Sets the specified Socket option to the specified value, represented as a byte array.
Public methodSetSocketOption(SocketOptionLevel, SocketOptionName, Int32)Sets the specified Socket option to the specified integer value.
Public methodSetSocketOption(SocketOptionLevel, SocketOptionName, Object)Sets the specified Socket option to the specified value, represented as an object.
Public methodShutdownDisables sends and receives on a Socket.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

The Socket class provides a rich set of methods and properties for network communications. The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration.

The Socket class follows the .NET Framework naming pattern for asynchronous methods. For example, the synchronous Receive method corresponds to the asynchronous BeginReceive and EndReceive methods.

If your application only requires one thread during execution, use the following methods, which are designed for synchronous operation mode.

  • If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the Listen method. The Accept method processes any incoming connection requests and returns a Socket that you can use to communicate data with the remote host. Use this returned Socket to call the Send or Receive method. Call the Bind method prior to calling the Listen method if you want to specify the local IP address and port number. Use a port number of zero if you want the underlying service provider to assign a free port for you. If you want to connect to a listening host, call the Connect method. To communicate data, call the Send or Receive method.

  • If you are using a connectionless protocol such as UDP, you do not need to listen for connections at all. Call the ReceiveFrom method to accept any incoming datagrams. Use the SendTo method to send datagrams to a remote host.

To process communications using separate threads during execution, use the following methods, which are designed for asynchronous operation mode.

If you perform multiple asynchronous operations on a socket, they do not necessarily complete in the order in which they are started.

When you are finished sending and receiving data, use the Shutdown method to disable the Socket. After calling Shutdown, call the Close method to release all resources associated with the Socket.

The Socket class allows you to configure your Socket using the SetSocketOption method. Retrieve these settings using the GetSocketOption method.

NoteNote

If you are writing a relatively simple application and do not require maximum performance, consider using TcpClient, TcpListener, and UdpClient. These classes provide a simpler and more user-friendly interface to Socket communications.

The following code example shows how the Socket class can be used to send data to an HTTP server and receive the response. This example blocks until the entire page is received.

#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Collections;
Socket^ ConnectSocket( String^ server, int port )
{
   Socket^ s = nullptr;
   IPHostEntry^ hostEntry = nullptr;

   // Get host related information.
   hostEntry = Dns::Resolve( server );

   // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid 
   // an exception that occurs when the host IP Address is not compatible with the address family 
   // (typical in the IPv6 case).
   IEnumerator^ myEnum = hostEntry->AddressList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      IPAddress^ address = safe_cast<IPAddress^>(myEnum->Current);
      IPEndPoint^ endPoint = gcnew IPEndPoint( address,port );
      Socket^ tmpS = gcnew Socket( endPoint->AddressFamily,SocketType::Stream,ProtocolType::Tcp );
      tmpS->Connect( endPoint );
      if ( tmpS->Connected )
      {
         s = tmpS;
         break;
      }
      else
      {
         continue;
      }
   }

   return s;
}


// This method requests the home page content for the specified server.
String^ SocketSendReceive( String^ server, int port )
{
   String^ request = String::Concat( "GET / HTTP/1.1\r\nHost: ", server, "\r\nConnection: Close\r\n\r\n" );
   array<Byte>^bytesSent = Encoding::ASCII->GetBytes( request );
   array<Byte>^bytesReceived = gcnew array<Byte>(256);

   // Create a socket connection with the specified server and port.
   Socket^ s = ConnectSocket( server, port );
   if ( s == nullptr )
      return ("Connection failed");


   // Send request to the server.
   s->Send( bytesSent, bytesSent->Length, static_cast<SocketFlags>(0) );

   // Receive the server home page content. 
   int bytes = 0;
   String^ strRetPage = String::Concat( "Default HTML page on ", server, ":\r\n" );
   do
   {
      bytes = s->Receive( bytesReceived, bytesReceived->Length, static_cast<SocketFlags>(0) );
      strRetPage = String::Concat( strRetPage, Encoding::ASCII->GetString( bytesReceived, 0, bytes ) );
   }
   while ( bytes > 0 );

   return strRetPage;
}

int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   String^ host;
   int port = 80;
   if ( args->Length == 1 )

   // If no server name is passed as argument to this program,  
   // use the current host name as default.
   host = Dns::GetHostName();
   else
      host = args[ 1 ];

   String^ result = SocketSendReceive( host, port );
   Console::WriteLine( result );
}

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

  • SocketPermission 

    To establish an outgoing connection or accept an incoming request.

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Instances of this class are thread safe.

Show:
© 2014 Microsoft