Socket.Connect Method

Definition

Establishes a connection to a remote host.

Overloads

Connect(EndPoint)

Establishes a connection to a remote host.

Connect(IPAddress, Int32)

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

Connect(IPAddress[], Int32)

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

Connect(String, Int32)

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

Connect(EndPoint)

Establishes a connection to a remote host.

public:
 void Connect(System::Net::EndPoint ^ remoteEP);
public void Connect (System.Net.EndPoint remoteEP);
member this.Connect : System.Net.EndPoint -> unit
Public Sub Connect (remoteEP As EndPoint)

Parameters

remoteEP
EndPoint

An EndPoint that represents the remote device.

Exceptions

remoteEP is null.

An error occurred when attempting to access the socket.

The Socket has been closed.

A caller higher in the call stack does not have permission for the requested operation.

The Socket has been placed in a listening state by calling Listen(Int32).

Examples

The following code example connects to a remote endpoint and then verifies the connection.

client->Connect( anEndPoint );
if (  !client->Connected )
{
   Console::WriteLine( "Winsock error: {0}", Convert::ToString(
      System::Runtime::InteropServices::Marshal::GetLastWin32Error() ) );
}
   
// This is how you can determine whether a socket is still connected.
bool blockingState = client->Blocking;
try
{
   array<Byte>^tmp = gcnew array<Byte>(1);
   client->Blocking = false;
   client->Send( tmp, 0, static_cast<SocketFlags>(0) );
   Console::WriteLine( L"Connected!" );
}
catch ( SocketException^ e ) 
{
   // 10035 == WSAEWOULDBLOCK
   if ( e->NativeErrorCode.Equals( 10035 ) )
   {
      Console::WriteLine( "Connected from an exception!" );
   }
   else
   {
      Console::WriteLine( "Disconnected: {0}!", e->NativeErrorCode );
   }
}
finally
{
   client->Blocking = blockingState;
}

Console::WriteLine( "Connected: {0}", client->Connected );
// .Connect throws an exception if unsuccessful
client.Connect(anEndPoint);

// This is how you can determine whether a socket is still connected.
bool blockingState = client.Blocking;
try
{
    byte [] tmp = new byte[1];

    client.Blocking = false;
    client.Send(tmp, 0, 0);
    Console.WriteLine("Connected!");
}
catch (SocketException e)
{
    // 10035 == WSAEWOULDBLOCK
    if (e.NativeErrorCode.Equals(10035))
    {
        Console.WriteLine("Still Connected, but the Send would block");
    }
    else
    {
        Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
    }
}
finally
{
    client.Blocking = blockingState;
}

Console.WriteLine("Connected: {0}", client.Connected);
    ' .Connect throws an exception if unsuccessful
    client.Connect(anEndPoint)
    
    ' This is how you can determine whether a socket is still connected.
    Dim blockingState As Boolean = client.Blocking
    Try
        Dim tmp(0) As Byte
        
        client.Blocking = False
        client.Send(tmp, 0, 0)
        Console.WriteLine("Connected!")
    Catch e As SocketException
        ' 10035 == WSAEWOULDBLOCK
        If e.NativeErrorCode.Equals(10035) Then
            Console.WriteLine("Still Connected, but the Send would block")
        Else
            Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode)
        End If
    Finally
        client.Blocking = blockingState
    End Try
    
    Console.WriteLine("Connected: {0}", client.Connected)

End Sub

Remarks

If you are using a connection-oriented protocol such as TCP, the Connect method synchronously establishes a network connection between LocalEndPoint and the specified remote endpoint. If you are using a connectionless protocol, Connect establishes a default remote host. After you call Connect, you can send data to the remote device with the Send method, or receive data from the remote device with the Receive method.

If you are using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. If you do call Connect, any datagrams that arrive from an address other than the specified default will be discarded. If you want to set your default remote host to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast, or Connect will throw a SocketException. If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

The Connect method will block, unless you specifically set the Blocking property to false prior to calling Connect. If you are using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection. Connectionless protocols will not throw an exception because they simply establish a default remote host. You can use SocketException.ErrorCode to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error. If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. Use the Poll method to determine when the Socket is finished connecting.

Note

If you are using a connection-oriented protocol and did not call Bind before calling Connect, the underlying service provider will assign the local network address and port number. If you are using a connectionless protocol, the service provider will not assign a local network address and port number until you complete a send or receive operation. If you want to change the default remote host, call Connect again with the desired endpoint.

Note

If the socket has been previously disconnected, then you cannot use this method to restore the connection. Use one of the asynchronous BeginConnect methods to reconnect. This is a limitation of the underlying provider.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in .NET Framework.

See also

Applies to

Connect(IPAddress, Int32)

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

public:
 void Connect(System::Net::IPAddress ^ address, int port);
public void Connect (System.Net.IPAddress address, int port);
member this.Connect : System.Net.IPAddress * int -> unit
Public Sub Connect (address As IPAddress, port As Integer)

Parameters

address
IPAddress

The IP address of the remote host.

port
Int32

The port number of the remote host.

Exceptions

address is null.

The port number is not valid.

An error occurred when attempting to access the socket.

The Socket has been closed.

This method is valid for sockets in the InterNetwork or InterNetworkV6 families.

The length of address is zero.

The Socket has been placed in a listening state by calling Listen(Int32).

Examples

The following code example connects to a remote endpoint and then verifies the connection.

// Synchronous connect using IPAddress to resolve the 
// host name.
static void Connect1( String^ host, int port )
{
   array<IPAddress^>^IPs = Dns::GetHostAddresses( host );
   Socket^ s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   Console::WriteLine( "Establishing Connection to {0}", host );
   s->Connect( IPs[ 0 ], port );
   Console::WriteLine( "Connection established" );
}
// Synchronous connect using IPAddress to resolve the
// host name.
public static void Connect1(string host, int port)
{
    IPAddress[] IPs = Dns.GetHostAddresses(host);

    Socket s = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream,
        ProtocolType.Tcp);

    Console.WriteLine("Establishing Connection to {0}",
        host);
    s.Connect(IPs[0], port);
    Console.WriteLine("Connection established");
}

Remarks

If you are using a connection-oriented protocol such as TCP, the Connect method synchronously establishes a network connection between LocalEndPoint and the specified remote endpoint. If you are using a connectionless protocol, Connect establishes a default remote host. After you call Connect you can send data to the remote device with the Send method, or receive data from the remote device with the Receive method.

If you are using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. If you do call Connect any datagrams that arrive from an address other than the specified default will be discarded. If you want to set your default remote host to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast, or Connect will throw a SocketException. If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Connect method will block, unless you specifically set the Blocking property to false prior to calling Connect. If you are using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection. Connectionless protocols will not throw an exception because they simply establish a default remote host. You can use SocketException.ErrorCode to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error. If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. Use the Poll method to determine when the Socket is finished connecting.

Note

If you are using a connection-oriented protocol and did not call Bind before calling Connect, the underlying service provider will assign the local network address and port number. If you are using a connectionless protocol, the service provider will not assign a local network address and port number until you complete a send or receive operation. If you want to change the default remote host, call Connect again with the desired endpoint.

Note

If the socket has been previously disconnected, then you cannot use this method to restore the connection. Use one of the asynchronous BeginConnect methods to reconnect. This is a limitation of the underlying provider.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in .NET Framework.

Applies to

Connect(IPAddress[], Int32)

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

public:
 void Connect(cli::array <System::Net::IPAddress ^> ^ addresses, int port);
public void Connect (System.Net.IPAddress[] addresses, int port);
member this.Connect : System.Net.IPAddress[] * int -> unit
Public Sub Connect (addresses As IPAddress(), port As Integer)

Parameters

addresses
IPAddress[]

The IP addresses of the remote host.

port
Int32

The port number of the remote host.

Exceptions

addresses is null.

The port number is not valid.

An error occurred when attempting to access the socket.

The Socket has been closed.

The socket is not in the InterNetwork or InterNetworkV6 families.

The length of address is zero.

The Socket has been placed in a listening state by calling Listen(Int32).

Examples

The following code example connects to a remote endpoint and then verifies the connection.

// Synchronous connect using Dns.ResolveToAddresses to 
// resolve the host name.
static void Connect2( String^ host, int port )
{
   array<IPAddress^>^IPs = Dns::GetHostAddresses( host );
   Socket^ s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   Console::WriteLine( "Establishing Connection to {0}", host );
   s->Connect( IPs, port );
   Console::WriteLine( "Connection established" );
}
// Synchronous connect using Dns.GetHostAddresses to
// resolve the host name.
public static void Connect2(string host, int port)
{
    IPAddress[] IPs = Dns.GetHostAddresses(host);

    Socket s = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream,
        ProtocolType.Tcp);
    Console.WriteLine("Establishing Connection to {0}",
        host);
    s.Connect(IPs, port);
    Console.WriteLine("Connection established");
}

Remarks

This method is typically used immediately after a call to GetHostAddresses, which can return multiple IP addresses for a single host. If you are using a connection-oriented protocol such as TCP, the Connect method synchronously establishes a network connection between LocalEndPoint and the specified remote endpoint. If you are using a connectionless protocol, Connect establishes a default remote host. After you call Connect you can send data to the remote device with the Send method, or receive data from the remote device with the Receive method.

If you are using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. If you do call Connect any datagrams that arrive from an address other than the specified default will be discarded. If you want to set your default remote host to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast, or Connect will throw a SocketException. If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Connect method will block, unless you specifically set the Blocking property to false prior to calling Connect. If you are using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection. Connectionless protocols will not throw an exception because they simply establish a default remote host. You can use SocketException.ErrorCode to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error. If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. Use the Poll method to determine when the Socket is finished connecting.

Note

If you are using a connection-oriented protocol and did not call Bind before calling Connect, the underlying service provider will assign the local network address and port number. If you are using a connectionless protocol, the service provider will not assign a local network address and port number until you complete a send or receive operation. If you want to change the default remote host, call Connect again with the desired endpoint.

Note

If the socket has been previously disconnected, then you cannot use this method to restore the connection. Use one of the asynchronous BeginConnect methods to reconnect. This is a limitation of the underlying provider.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in .NET Framework.

Applies to

Connect(String, Int32)

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

public:
 void Connect(System::String ^ host, int port);
public void Connect (string host, int port);
member this.Connect : string * int -> unit
Public Sub Connect (host As String, port As Integer)

Parameters

host
String

The name of the remote host.

port
Int32

The port number of the remote host.

Exceptions

host is null.

The port number is not valid.

An error occurred when attempting to access the socket.

The Socket has been closed.

The socket is not in the InterNetwork or InterNetworkV6 families.

The Socket has been placed in a listening state by calling Listen(Int32).

Examples

The following code example connects to a remote endpoint and then verifies the connection.

// Synchronous connect using host name (resolved by the 
// Connect call.)
static void Connect3( String^ host, int port )
{
   Socket^ s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   Console::WriteLine( "Establishing Connection to {0}", host );
   s->Connect( host, port );
   Console::WriteLine( "Connection established" );
}
// Synchronous connect using host name (resolved by the
// Connect call.)
public static void Connect3(string host, int port)
{
    Socket s = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream,
        ProtocolType.Tcp);

    Console.WriteLine("Establishing Connection to {0}",
        host);
    s.Connect(host, port);
    Console.WriteLine("Connection established");
}

Remarks

If you're using a connection-oriented protocol such as TCP, the Connect method synchronously establishes a network connection between LocalEndPoint and the specified remote host. If you are using a connectionless protocol, Connect establishes a default remote host. After you call Connect you can send data to the remote device with the Send method, or receive data from the remote device with the Receive method.

If you're using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. If you do call Connect any datagrams that arrive from an address other than the specified default will be discarded. If you want to set your default remote host to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast, or Connect will throw a SocketException. If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

The Connect method will block, unless you specifically set the Blocking property to false prior to calling Connect. If you're using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection. Connectionless protocols will not throw an exception because they simply establish a default remote host. You can use SocketException.ErrorCode to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error. If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. Use the Poll method to determine when the Socket is finished connecting.

If IPv6 is enabled and the Connect(String, Int32) method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address.

Note

If you're using a connection-oriented protocol and did not call Bind before calling Connect, the underlying service provider will assign the local network address and port number. If you are using a connectionless protocol, the service provider will not assign a local network address and port number until you complete a send or receive operation. If you want to change the default remote host, call Connect again with the desired endpoint.

Note

If the socket has been previously disconnected, then you cannot use this method to restore the connection. Use one of the asynchronous BeginConnect methods to reconnect. This is a limitation of the underlying provider.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in .NET Framework.

Applies to