Michael Pittino
Michael Pittino

Reputation: 2178

TcpClient throws SocketException

I got the following code:

public static readonly IPEndPoint RootNode = new IPEndPoint(IPAddress.Parse("213.226.18.82"), 8333);

public static void Main(string[] args)
{
    TcpClient tcpClient = new TcpClient(RootNode);
}

This throws a SocketException with the message The requested address is not valid in its context. Now whats strange is that this code works:

public static readonly IPEndPoint RootNode = new IPEndPoint(IPAddress.Parse("213.226.18.82"), 8333);

public static void Main(string[] args)
{
    TcpClient tcpClient = new TcpClient();

    tcpClient.Connect(RootNode);
}

What is the difference here?

Upvotes: 1

Views: 787

Answers (2)

Maximilian Gerhardt
Maximilian Gerhardt

Reputation: 5353

In the documentation at https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.tcpclient%28v=vs.110%29.aspx it talks about this constructor:

TcpClient(IPEndPoint): Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.

So here it says that it will bind it to the local adress, like you were listening on some port maybe. The Connect() command will connect you to a remote endpont. That should be the difference.

Upvotes: 3

Jakub Lortz
Jakub Lortz

Reputation: 14896

The constructor

Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.

The Connect method

Connects the client to a remote TCP host using the specified remote network endpoint.

Upvotes: 0

Related Questions