Socket Class

Socket Class

 

Implements the Berkeley sockets interface.

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

System.Object
  System.Net.Sockets.Socket

public class Socket : IDisposable

NameDescription
System_CAPS_pubmethodSocket(AddressFamily, SocketType, ProtocolType)

Initializes a new instance of the Socket class using the specified address family, socket type and protocol.

System_CAPS_pubmethodSocket(SocketInformation)

Initializes a new instance of the Socket class using the specified value returned from DuplicateAndClose.

System_CAPS_pubmethodSocket(SocketType, ProtocolType)

Initializes a new instance of the Socket class using the specified socket type and protocol.

NameDescription
System_CAPS_pubpropertyAddressFamily

Gets the address family of the Socket.

System_CAPS_pubpropertyAvailable

Gets the amount of data that has been received from the network and is available to be read.

System_CAPS_pubpropertyBlocking

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

System_CAPS_pubpropertyConnected

Gets a value that indicates whether a Socket is connected to a remote host as of the last Send or Receive operation.

System_CAPS_pubpropertyDontFragment

Gets or sets a Boolean value that specifies whether the Socket allows Internet Protocol (IP) datagrams to be fragmented.

System_CAPS_pubpropertyDualMode

Gets or sets a Boolean value that specifies whether the Socket is a dual-mode socket used for both IPv4 and IPv6.

System_CAPS_pubpropertyEnableBroadcast

Gets or sets a Boolean value that specifies whether the Socket can send or receive broadcast packets.

System_CAPS_pubpropertyExclusiveAddressUse

Gets or sets a Boolean value that specifies whether the Socket allows only one process to bind to a port.

System_CAPS_pubpropertyHandle

Gets the operating system handle for the Socket.

System_CAPS_pubpropertyIsBound

Gets a value that indicates whether the Socket is bound to a specific local port.

System_CAPS_pubpropertyLingerState

Gets or sets a value that specifies whether the Socket will delay closing a socket in an attempt to send all pending data.

System_CAPS_pubpropertyLocalEndPoint

Gets the local endpoint.

System_CAPS_pubpropertyMulticastLoopback

Gets or sets a value that specifies whether outgoing multicast packets are delivered to the sending application.

System_CAPS_pubpropertyNoDelay

Gets or sets a Boolean value that specifies whether the stream Socket is using the Nagle algorithm.

System_CAPS_pubpropertySystem_CAPS_staticOSSupportsIPv4

Indicates whether the underlying operating system and network adaptors support Internet Protocol version 4 (IPv4).

System_CAPS_pubpropertySystem_CAPS_staticOSSupportsIPv6

Indicates whether the underlying operating system and network adaptors support Internet Protocol version 6 (IPv6).

System_CAPS_pubpropertyProtocolType

Gets the protocol type of the Socket.

System_CAPS_pubpropertyReceiveBufferSize

Gets or sets a value that specifies the size of the receive buffer of the Socket.

System_CAPS_pubpropertyReceiveTimeout

Gets or sets a value that specifies the amount of time after which a synchronous Receive call will time out.

System_CAPS_pubpropertyRemoteEndPoint

Gets the remote endpoint.

System_CAPS_pubpropertySendBufferSize

Gets or sets a value that specifies the size of the send buffer of the Socket.

System_CAPS_pubpropertySendTimeout

Gets or sets a value that specifies the amount of time after which a synchronous Send call will time out.

System_CAPS_pubpropertySocketType

Gets the type of the Socket.

System_CAPS_pubpropertySystem_CAPS_staticSupportsIPv4

Obsolete.Gets a value indicating whether IPv4 support is available and enabled on the current host.

System_CAPS_pubpropertySystem_CAPS_staticSupportsIPv6

Obsolete.Gets a value that indicates whether the Framework supports IPv6 for certain obsolete Dns members.

System_CAPS_pubpropertyTtl

Gets or sets a value that specifies the Time To Live (TTL) value of Internet Protocol (IP) packets sent by the Socket.

System_CAPS_pubpropertyUseOnlyOverlappedIO

Specifies whether the socket should only use Overlapped I/O mode.

NameDescription
System_CAPS_pubmethodAccept()

Creates a new Socket for a newly created connection.

System_CAPS_pubmethodAcceptAsync(SocketAsyncEventArgs)

Begins an asynchronous operation to accept an incoming connection attempt.

System_CAPS_pubmethodBeginAccept(AsyncCallback, Object)

Begins an asynchronous operation to accept an incoming connection attempt.

System_CAPS_pubmethodBeginAccept(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.

System_CAPS_pubmethodBeginAccept(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.

System_CAPS_pubmethodBeginConnect(EndPoint, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection.

System_CAPS_pubmethodBeginConnect(IPAddress, Int32, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection. The host is specified by an IPAddress and a port number.

System_CAPS_pubmethodBeginConnect(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.

System_CAPS_pubmethodBeginConnect(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.

System_CAPS_pubmethodBeginDisconnect(Boolean, AsyncCallback, Object)

Begins an asynchronous request to disconnect from a remote endpoint.

System_CAPS_pubmethodBeginReceive(Byte[], Int32, Int32, SocketFlags, AsyncCallback, Object)

Begins to asynchronously receive data from a connected Socket.

System_CAPS_pubmethodBeginReceive(Byte[], Int32, Int32, SocketFlags, SocketError, AsyncCallback, Object)

Begins to asynchronously receive data from a connected Socket.

System_CAPS_pubmethodBeginReceive(IList<ArraySegment<Byte>>, SocketFlags, AsyncCallback, Object)

Begins to asynchronously receive data from a connected Socket.

System_CAPS_pubmethodBeginReceive(IList<ArraySegment<Byte>>, SocketFlags, SocketError, AsyncCallback, Object)

Begins to asynchronously receive data from a connected Socket.

System_CAPS_pubmethodBeginReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object)

Begins to asynchronously receive data from a specified network device.

System_CAPS_pubmethodBeginReceiveMessageFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object)

Begins 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..

System_CAPS_pubmethodBeginSend(Byte[], Int32, Int32, SocketFlags, AsyncCallback, Object)

Sends data asynchronously to a connected Socket.

System_CAPS_pubmethodBeginSend(Byte[], Int32, Int32, SocketFlags, SocketError, AsyncCallback, Object)

Sends data asynchronously to a connected Socket.

System_CAPS_pubmethodBeginSend(IList<ArraySegment<Byte>>, SocketFlags, AsyncCallback, Object)

Sends data asynchronously to a connected Socket.

System_CAPS_pubmethodBeginSend(IList<ArraySegment<Byte>>, SocketFlags, SocketError, AsyncCallback, Object)

Sends data asynchronously to a connected Socket.

System_CAPS_pubmethodBeginSendFile(String, AsyncCallback, Object)

Sends the file fileName to a connected Socket object using the UseDefaultWorkerThread flag.

System_CAPS_pubmethodBeginSendFile(String, Byte[], Byte[], TransmitFileOptions, AsyncCallback, Object)

Sends a file and buffers of data asynchronously to a connected Socket object.

System_CAPS_pubmethodBeginSendTo(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object)

Sends data asynchronously to a specific remote host.

System_CAPS_pubmethodBind(EndPoint)

Associates a Socket with a local endpoint.

System_CAPS_pubmethodSystem_CAPS_staticCancelConnectAsync(SocketAsyncEventArgs)

Cancels an asynchronous request for a remote host connection.

System_CAPS_pubmethodClose()

Closes the Socket connection and releases all associated resources.

System_CAPS_pubmethodClose(Int32)

Closes the Socket connection and releases all associated resources with a specified timeout to allow queued data to be sent.

System_CAPS_pubmethodConnect(EndPoint)

Establishes a connection to a remote host.

System_CAPS_pubmethodConnect(IPAddress, Int32)

Establishes a connection to a remote host. The host is specified by an IP address and a port number.

System_CAPS_pubmethodConnect(IPAddress[], Int32)

Establishes a connection to a remote host. The host is specified by an array of IP addresses and a port number.

System_CAPS_pubmethodConnect(String, Int32)

Establishes a connection to a remote host. The host is specified by a host name and a port number.

System_CAPS_pubmethodConnectAsync(SocketAsyncEventArgs)

Begins an asynchronous request for a connection to a remote host.

System_CAPS_pubmethodSystem_CAPS_staticConnectAsync(SocketType, ProtocolType, SocketAsyncEventArgs)

Begins an asynchronous request for a connection to a remote host.

System_CAPS_pubmethodDisconnect(Boolean)

Closes the socket connection and allows reuse of the socket.

System_CAPS_pubmethodDisconnectAsync(SocketAsyncEventArgs)

Begins an asynchronous request to disconnect from a remote endpoint.

System_CAPS_pubmethodDispose()

Releases all resources used by the current instance of the Socket class.

System_CAPS_protmethodDispose(Boolean)

Releases the unmanaged resources used by the Socket, and optionally disposes of the managed resources.

System_CAPS_pubmethodDuplicateAndClose(Int32)

Duplicates the socket reference for the target process, and closes the socket for this process.

System_CAPS_pubmethodEndAccept(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.

System_CAPS_pubmethodEndAccept(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.

System_CAPS_pubmethodEndAccept(IAsyncResult)

Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.

System_CAPS_pubmethodEndConnect(IAsyncResult)

Ends a pending asynchronous connection request.

System_CAPS_pubmethodEndDisconnect(IAsyncResult)

Ends a pending asynchronous disconnect request.

System_CAPS_pubmethodEndReceive(IAsyncResult)

Ends a pending asynchronous read.

System_CAPS_pubmethodEndReceive(IAsyncResult, SocketError)

Ends a pending asynchronous read.

System_CAPS_pubmethodEndReceiveFrom(IAsyncResult, EndPoint)

Ends a pending asynchronous read from a specific endpoint.

System_CAPS_pubmethodEndReceiveMessageFrom(IAsyncResult, SocketFlags, EndPoint, IPPacketInformation)

Ends a pending asynchronous read from a specific endpoint. This method also reveals more information about the packet than EndReceiveFrom.

System_CAPS_pubmethodEndSend(IAsyncResult)

Ends a pending asynchronous send.

System_CAPS_pubmethodEndSend(IAsyncResult, SocketError)

Ends a pending asynchronous send.

System_CAPS_pubmethodEndSendFile(IAsyncResult)

Ends a pending asynchronous send of a file.

System_CAPS_pubmethodEndSendTo(IAsyncResult)

Ends a pending asynchronous send to a specific location.

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethodFinalize()

Frees resources used by the Socket class.(Overrides Object.Finalize().)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetSocketOption(SocketOptionLevel, SocketOptionName)

Returns the value of a specified Socket option, represented as an object.

System_CAPS_pubmethodGetSocketOption(SocketOptionLevel, SocketOptionName, Byte[])

Returns the specified Socket option setting, represented as a byte array.

System_CAPS_pubmethodGetSocketOption(SocketOptionLevel, SocketOptionName, Int32)

Returns the value of the specified Socket option in an array.

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodIOControl(Int32, Byte[], Byte[])

Sets low-level operating modes for the Socket using numerical control codes.

System_CAPS_pubmethodIOControl(IOControlCode, Byte[], Byte[])

Sets low-level operating modes for the Socket using the IOControlCode enumeration to specify control codes.

System_CAPS_pubmethodListen(Int32)

Places a Socket in a listening state.

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethodPoll(Int32, SelectMode)

Determines the status of the Socket.

System_CAPS_pubmethodReceive(Byte[])

Receives data from a bound Socket into a receive buffer.

System_CAPS_pubmethodReceive(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.

System_CAPS_pubmethodReceive(Byte[], Int32, Int32, SocketFlags, SocketError)

Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.

System_CAPS_pubmethodReceive(Byte[], Int32, SocketFlags)

Receives the specified number of bytes of data from a bound Socket into a receive buffer, using the specified SocketFlags.

System_CAPS_pubmethodReceive(Byte[], SocketFlags)

Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.

System_CAPS_pubmethodReceive(IList<ArraySegment<Byte>>)

Receives data from a bound Socket into the list of receive buffers.

System_CAPS_pubmethodReceive(IList<ArraySegment<Byte>>, SocketFlags)

Receives data from a bound Socket into the list of receive buffers, using the specified SocketFlags.

System_CAPS_pubmethodReceive(IList<ArraySegment<Byte>>, SocketFlags, SocketError)

Receives data from a bound Socket into the list of receive buffers, using the specified SocketFlags.

System_CAPS_pubmethodReceiveAsync(SocketAsyncEventArgs)

Begins an asynchronous request to receive data from a connected Socket object.

System_CAPS_pubmethodReceiveFrom(Byte[], EndPoint)

Receives a datagram into the data buffer and stores the endpoint.

System_CAPS_pubmethodReceiveFrom(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.

System_CAPS_pubmethodReceiveFrom(Byte[], Int32, SocketFlags, EndPoint)

Receives the specified number of bytes into the data buffer, using the specified SocketFlags, and stores the endpoint.

System_CAPS_pubmethodReceiveFrom(Byte[], SocketFlags, EndPoint)

Receives a datagram into the data buffer, using the specified SocketFlags, and stores the endpoint.

System_CAPS_pubmethodReceiveFromAsync(SocketAsyncEventArgs)

Begins to asynchronously receive data from a specified network device.

System_CAPS_pubmethodReceiveMessageFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, IPPacketInformation)

Receives 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.

System_CAPS_pubmethodReceiveMessageFromAsync(SocketAsyncEventArgs)

Begins 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.

System_CAPS_pubmethodSystem_CAPS_staticSelect(IList, IList, IList, Int32)

Determines the status of one or more sockets.

System_CAPS_pubmethodSend(Byte[])

Sends data to a connected Socket.

System_CAPS_pubmethodSend(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.

System_CAPS_pubmethodSend(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

System_CAPS_pubmethodSend(Byte[], Int32, SocketFlags)

Sends the specified number of bytes of data to a connected Socket, using the specified SocketFlags.

System_CAPS_pubmethodSend(Byte[], SocketFlags)

Sends data to a connected Socket using the specified SocketFlags.

System_CAPS_pubmethodSend(IList<ArraySegment<Byte>>)

Sends the set of buffers in the list to a connected Socket.

System_CAPS_pubmethodSend(IList<ArraySegment<Byte>>, SocketFlags)

Sends the set of buffers in the list to a connected Socket, using the specified SocketFlags.

System_CAPS_pubmethodSend(IList<ArraySegment<Byte>>, SocketFlags, SocketError)

Sends the set of buffers in the list to a connected Socket, using the specified SocketFlags.

System_CAPS_pubmethodSendAsync(SocketAsyncEventArgs)

Sends data asynchronously to a connected Socket object.

System_CAPS_pubmethodSendFile(String)

Sends the file fileName to a connected Socket object with the UseDefaultWorkerThread transmit flag.

System_CAPS_pubmethodSendFile(String, Byte[], Byte[], TransmitFileOptions)

Sends the file fileName and buffers of data to a connected Socket object using the specified TransmitFileOptions value.

System_CAPS_pubmethodSendPacketsAsync(SocketAsyncEventArgs)

Sends a collection of files or in memory data buffers asynchronously to a connected Socket object.

System_CAPS_pubmethodSendTo(Byte[], EndPoint)

Sends data to the specified endpoint.

System_CAPS_pubmethodSendTo(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.

System_CAPS_pubmethodSendTo(Byte[], Int32, SocketFlags, EndPoint)

Sends the specified number of bytes of data to the specified endpoint using the specified SocketFlags.

System_CAPS_pubmethodSendTo(Byte[], SocketFlags, EndPoint)

Sends data to a specific endpoint using the specified SocketFlags.

System_CAPS_pubmethodSendToAsync(SocketAsyncEventArgs)

Sends data asynchronously to a specific remote host.

System_CAPS_pubmethodSetIPProtectionLevel(IPProtectionLevel)

Set the IP protection level on a socket.

System_CAPS_pubmethodSetSocketOption(SocketOptionLevel, SocketOptionName, Boolean)

Sets the specified Socket option to the specified Boolean value.

System_CAPS_pubmethodSetSocketOption(SocketOptionLevel, SocketOptionName, Byte[])

Sets the specified Socket option to the specified value, represented as a byte array.

System_CAPS_pubmethodSetSocketOption(SocketOptionLevel, SocketOptionName, Int32)

Sets the specified Socket option to the specified integer value.

System_CAPS_pubmethodSetSocketOption(SocketOptionLevel, SocketOptionName, Object)

Sets the specified Socket option to the specified value, represented as an object.

System_CAPS_pubmethodShutdown(SocketShutdown)

Disables sends and receives on a Socket.

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

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.

System_CAPS_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;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

public class GetSocket
{
    private static Socket ConnectSocket(string server, int port)
    {
        Socket s = null;
        IPHostEntry hostEntry = null;

        // Get host related information.
        hostEntry = Dns.GetHostEntry(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).
        foreach(IPAddress address in hostEntry.AddressList)
        {
            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket tempSocket = 
                new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            tempSocket.Connect(ipe);

            if(tempSocket.Connected)
            {
                s = tempSocket;
                break;
            }
            else
            {
                continue;
            }
        }
        return s;
    }

    // This method requests the home page content for the specified server.
    private static string SocketSendReceive(string server, int port) 
    {
        string request = "GET / HTTP/1.1\r\nHost: " + server + 
            "\r\nConnection: Close\r\n\r\n";
        Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
        Byte[] bytesReceived = new Byte[256];

        // Create a socket connection with the specified server and port.
        Socket s = ConnectSocket(server, port);

        if (s == null)
            return ("Connection failed");

        // Send request to the server.
        s.Send(bytesSent, bytesSent.Length, 0);  

        // Receive the server home page content.
        int bytes = 0;
        string page = "Default HTML page on " + server + ":\r\n";

        // The following will block until te page is transmitted.
        do {
            bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
            page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
        }
        while (bytes > 0);

        return page;
    }

    public static void Main(string[] args) 
    {
        string host;
        int port = 80;

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

        string result = SocketSendReceive(host, port); 
        Console.WriteLine(result);
    }
}

SocketPermission

To establish an outgoing connection or accept an incoming request.

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.1

Instances of this class are thread safe.

Return to top
Show:
© 2016 Microsoft