This documentation is archived and is not being maintained.

Using Client Sockets

Before you can initiate a conversation through a Socket, you must create a data pipe between your application and the remote device. Although other network address families and protocols exist, this example shows how to create a TCP/IP connection to a remote service.

TCP/IP uses a network address and a service port number to uniquely identify a service. The network address identifies a specific device on the network; the port number identifies the specific service on that device to connect to. The combination of network address and service port is called an endpoint, which is represented in the .NET Framework by the EndPoint class. A descendant of EndPoint is defined for each supported address family; for the IP address family, the class is IPEndPoint.

The Dns class provides domain-name services to applications that use TCP/IP Internet services. The Resolve method queries a DNS server to map a user-friendly domain name (such as "") to a numeric Internet address (such as Resolve returns an IPHostEnty that contains a list of addresses and aliases for the requested name. In most cases, you can use the first address returned in the AddressList array. The following code gets an IPAddress containing the IP address for the server

Dim ipHostInfo As IPHostEntry = Dns.Resolve("")
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)

IPHostEntry ipHostInfo = Dns.Resolve("");
IPAddress ipAddress = ipHostInfo.AddressList[0];

The Internet Assigned Numbers Authority (IANA) defines port numbers for common services (for more information, see Other services can have registered port numbers in the range 1,024 to 65,535. The following code combines the IP address for with a port number to create a remote endpoint for a connection.

Dim ipe As New IPEndPoint(ipAddress, 11000)

IPEndPoint ipe = new IPEndPoint(ipAddress,11000);

After determining the address of the remote device and choosing a port to use for the connection, the application can attempt to establish a connection with the remote device. The following example uses an existing IPEndPoint to connect to a remote device and catches any exceptions that are thrown.

Catch ae As ArgumentNullException
    Console.WriteLine("ArgumentNullException : {0}", _
Catch se As SocketException
    Console.WriteLine("SocketException : {0}", se.ToString())
Catch e As Exception
    Console.WriteLine("Unexpected exception : {0}", e.ToString())
End Try

try {
} catch(ArgumentNullException ae) {
    Console.WriteLine("ArgumentNullException : {0}", ae.ToString());
} catch(SocketException se) {
    Console.WriteLine("SocketException : {0}", se.ToString());
} catch(Exception e) {
    Console.WriteLine("Unexpected exception : {0}", e.ToString());

See Also

Using a Synchronous Client Socket | Using an Asynchronous Client Socket | Creating Sockets | Sockets