Socket Class

Provides the managed implementation of the socket API. The Socket class allows you to perform network operations. It supports both connection-oriented and connectionless communication protocols.

Fields

Name Description
Socket.SocketError Represents a socket error that occurred.

Constructors

Signature Description
public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) Initializes a new instance of the Socket class using the specified address family, socket type, and protocol.
public Socket(SocketInformation socketInformation) Initializes a new instance of the Socket class from the specified SocketInformation object.

Properties

Name Description
Available Gets the number of bytes available to be read from the socket.
Blocking Gets or sets a value indicating whether the Socket is in blocking or non-blocking mode.
Connected Gets a value indicating whether the Socket is connected to a remote host.
DontFragment Gets or sets a value indicating whether the Socket can send data packets that set the Don't Fragment flag.
DontLinger Gets or sets a value indicating whether a Socket will linger after closing.
DualMode Gets or sets a value indicating whether the Socket supports both IPv4 and IPv6.
EnableBroadcast Gets or sets a value indicating whether broadcast messages are sent and received by the Socket.
Handle Gets the native socket handle.
IsBound Gets a value indicating whether the Socket is bound to a local endpoint.
LingerState Gets or sets a LingerOption object that controls lingering after a Socket closes.
MulticastLoopback Gets or sets a value indicating whether multicast packets are sent back to the local computer when the application is listening on the same multicast group.
NoDelay Gets or sets a value indicating whether the Nagle algorithm is disabled for this Socket.
ProtocolType Gets the protocol type of the Socket.
ProtocolOptions Gets or sets the ProtocolOptions for the Socket.
ReceiveBufferSize Gets or sets the size of the buffer for incoming data.
ReceiveTimeout Gets or sets the time-out value in milliseconds for blocking Socket receive operations.
SendBufferSize Gets or sets the size of the buffer for outgoing data.
SendTimeout Gets or sets the time-out value in milliseconds for blocking Socket send operations.
Ttl Gets or sets the time-to-live value for the Socket.

Methods

Signature Description
Accept() Accepts a pending connection request.
Bind(EndPoint localEP) Binds a Socket to a local endpoint.
Close() Releases all resources used by the Socket.
Connect(EndPoint remoteEP) Connects the Socket to a remote endpoint.
Disconnect(bool reuseSocket) Disconnects the Socket from the current connection.
EndAccept(IAsyncResult asyncResult) Completes an asynchronous accept operation.
EndConnect(IAsyncResult asyncResult) Completes an asynchronous connect operation.
EndReceive(IAsyncResult asyncResult) Completes an asynchronous receive operation.
EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint remoteEP) Completes an asynchronous receive from operation.
EndSend(IAsyncResult asyncResult) Completes an asynchronous send operation.
EndSendTo(IAsyncResult asyncResult) Completes an asynchronous send to operation.
GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName) Gets a socket option.
IOControlControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue) Sends a control message to the underlying system, which returns any data or status information that the system provides.
Listen(int backlog) Puts a Socket into listening mode.
Receive(byte[] buffer) Receives data from the Socket into a buffer.
ReceiveFrom(byte[] buffer, ref EndPoint remoteEP) Receives data from a Socket into a buffer and retrieves the endpoint that sent the data.
Send(byte[] buffer) Sends the entire buffer containing data to the remote device.
SendTo(byte[] buffer, EndPoint remoteEP) Sends data to a specific endpoint.
SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue) Sets a socket option.
Shutdown(SocketShutdown how) Disables sends and/or receives on the Socket.

Example Usage

The following example demonstrates how to create a simple TCP client socket, connect to a server, send a message, and receive a response.


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

public class SimpleTcpClient
{
    public static void Main(string[] args)
    {
        // Define server endpoint
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        int port = 13000;
        IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

        // Create a TCP/IP socket.
        using (Socket sender = new Socket(
            ipAddress.AddressFamily,
            SocketType.Stream,
            ProtocolType.Tcp))
        {
            try
            {
                // Connect to the remote endpoint.
                sender.Connect(remoteEP);

                // Data buffer for incoming data.
                byte[] bytes = new byte[1024];

                // Send message to the server.
                string messageToSend = "Hello, Server!";
                byte[] msg = Encoding.ASCII.GetBytes(messageToSend + "\0");

                // Send the data through the socket.
                int bytesSent = sender.Send(msg);

                // Receive the response from the server.
                int bytesRec = sender.Receive(bytes);
                string response = Encoding.ASCII.GetString(bytes, 0, bytesRec);

                Console.WriteLine("Echoed test sent by client: {0}", response);

                // Release the socket.
                sender.Shutdown(SocketShutdown.Both);
            }
            catch (ArgumentNullException aea)
            {
                Console.WriteLine("ArgumentNullException : {0}", aea.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }
        }

        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();
    }
}