Socket Class
.NET Framework Class Library
Socket Class

Implements the Berkeley sockets interface.

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)
Visual Basic (Declaration)
Public Class Socket _
    Implements IDisposable
Visual Basic (Usage)
Dim instance As Socket
C#
public class Socket : IDisposable
Visual C++
public ref class Socket : IDisposable
JScript
public class Socket implements IDisposable

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.

Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note: Not all socket options are supported on all device operating systems.

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.

Visual Basic
Imports System
Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports Microsoft.VisualBasic

Public Class GetSocket

   Private Shared Function ConnectSocket(server As String, port As Integer) As Socket
      Dim s As Socket = Nothing
      Dim hostEntry As IPHostEntry = Nothing      

         ' 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 host IP Address is not compatible with the address family
         ' (typical in the IPv6 case).
      Dim address As IPAddress

        For Each address In  hostEntry.AddressList
            Dim endPoint As New IPEndPoint(address, port)
            Dim tempSocket As New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)

            tempSocket.Connect(endPoint)

            If tempSocket.Connected Then
               s = tempSocket
               Exit For
            End If

         Next address

      Return s
   End Function 


   ' This method requests the home page content for the specified server.

   Private Shared Function SocketSendReceive(server As String, port As Integer) As String
      'Set up variables and String to write to the server.
      Dim ascii As Encoding = Encoding.ASCII
      Dim request As String = "GET / HTTP/1.1" + ControlChars.Cr + ControlChars.Lf + "Host: " + server + ControlChars.Cr + ControlChars.Lf + "Connection: Close" + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf
      Dim bytesSent As [Byte]() = ascii.GetBytes(request)
      Dim bytesReceived(255) As [Byte]

      ' Create a socket connection with the specified server and port.
      Dim s As Socket = ConnectSocket(server, port)

      If s Is Nothing Then
         Return "Connection failed"
      End If 
      ' Send request to the server.
      s.Send(bytesSent, bytesSent.Length, 0)

      ' Receive the server  home page content.
      Dim bytes As Int32

      ' Read the first 256 bytes.
      Dim page as [String] = "Default HTML page on " + server + ":" + ControlChars.Cr + ControlChars.Lf

      ' The following will block until the page is transmitted.
      Do
         bytes = s.Receive(bytesReceived, bytesReceived.Length, 0)
            page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes)
      Loop While bytes > 0

      Return page
   End Function 

   'Entry point which delegates to C-style main Private Function
   Public Overloads Shared Sub Main()
      Main(System.Environment.GetCommandLineArgs())
   End Sub


   Overloads Private Shared Sub Main(args() As String)
      Dim host As String
      Dim port As Integer = 80

      If args.Length = 1 Then
         ' 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)
      End If 

      Dim result As String = SocketSendReceive(host, port)

      Console.WriteLine(result)
   End Sub 'Main
End Class  

C#
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);
    }
}

Visual C++
#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 );
}

CPP_OLD
#using <mscorlib.dll>
#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 = 0;
    IPHostEntry* hostEntry = 0;

    // 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 = __try_cast<IPAddress*>(myEnum->Current);
        IPEndPoint* endPoint = new IPEndPoint(address, port);
        Socket* tmpS = new 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(S"GET / HTTP/1.1\r\nHost: ", server,
        S"\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 == 0)
        return (S"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(S"Default HTML page on ", server, S":\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() {
    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);
}
  • SocketPermission 

    To establish an outgoing connection or accept an incoming request.

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

Instances of this class are thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

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

.NET Framework

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

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Using the Socket class to request the NetBios name of a device over UDP      Joel Ivory Johnson   |   Edit   |   Show History

Many Windows and non-Windows based network devices will respond with their name to a NetBios name request sent on UDP port 137. The following code demonstrates the use of the Socket class to send such a request. The program takes as it's only command line argument the IP address of a target machine. The use of the ReceiveTimeOut socket option is needed to prevent the program from waiting indefinitly should the specified IP address not belong to a machine or should that machine not respond with it's NetBios name.

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

namespace UDPSocketExample
{
class Program
{
// The following byte stream contains the necessary message
// to request a NetBios name from a machine
static byte[] NameRequest = new byte[]{
0x80, 0x94, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x20, 0x43, 0x4b, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x00, 0x00, 0x21,
0x00, 0x01 };


static void Main(string[] args)
{
if (args.Length < 1)
{
Console.Out.WriteLine("Usage: xxx.exe [IP Address]");
return ;
}
byte[] receiveBuffer = new byte[1024];
Socket requestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
requestSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
IPAddress[] addressList = Dns.GetHostAddresses(args[0]);
if (addressList.Length == 0)
{
Console.Out.WriteLine("The requested host could not be found ({0})", args[0]);
return;
}

EndPoint remoteEndpoint = new IPEndPoint(addressList[0],137);
IPEndPoint originEndpoint = new IPEndPoint(IPAddress.Any, 0);
requestSocket.Bind(originEndpoint);
requestSocket.SendTo(NameRequest, remoteEndpoint);
try
{

int receivedByteCount = requestSocket.ReceiveFrom(receiveBuffer, ref remoteEndpoint);
if (receivedByteCount >= 90)
{
Encoding enc = new ASCIIEncoding();
string dnsEntryName = Dns.GetHostByAddress(addressList[0]).HostName;
string deviceName = enc.GetString(receiveBuffer, 57, 16).Trim();
string networkName = enc.GetString(receiveBuffer, 75, 16).Trim();
Console.Out.WriteLine(String.Format( "Request Sent to :{0}\n\r"+
"NetBios Query Result:{1}\r\n"+
"Reverse DNS Lookup :{2}\r\n", args[0],deviceName,dnsEntryName));
}
}
catch (SocketException )
{
Console.Out.WriteLine(String.Format("The device identified by {0} could not be identified by a NetBios name",args[0]));
}
}
}
}


Tags What's this?: socket (x) udp (x) Add a tag
Flag as ContentBug
Processing
Page view tracker