开发者

Difference between new TcpClient(MachineName, port) and new TcpClient(new IPEndpoint(..., Port))

Hej Hej,

I have a .Net program that has to run on a cluster of server 2008. To find out the 开发者_如何学编程right IP I resolve the dns by

GetHostEntry(VarDefinedInfConfig).AddressList(0)

but when I am converting my old code (this code picks the wrong IP) dns.GetHostName().AddressList(0) => this returns a virtual IP and not the right one.

So I changed my TcpListener to (dns is parameter from config)

Dim listener As TcpListener = New TcpListener(New IPEndPoint(Net.Dns.GetHostEntry(dns).AddressList(0), 8001))
listener.Start()

In the old way a tcpclient was defined by this code

  Dim client As TcpClient = New TcpClient(Environment.MachineName, 8001)
  Console.WriteLine("Done...")
  client.Close()

This also connects to the wrong IP so I found the overload of TcpClient and used that one

New way:

 Dim client2 As TcpClient = New TcpClient(New IPEndPoint(Net.Dns.GetHostEntry(dns).AddressList(0), 8001))
    Console.WriteLine("Done")
    client2.Close()

But when I use the second one I got the exception "Only one usage of each socket address (protocol/network address / port) is normally permitted.

Weird thing is if I get the IP from the MachineName is exactly the same as the ip retreived from dns with parameter.

Does anybody know the cause of this exception? Normally they should have the same result.

Greetz,

Jonathan


Is it possible that you overlooked the main difference between the 2 mentioned TcpClient constructors (MSDN)?:

TcpClient(String, Int32) .. connects to the specified port on the specified host.

TcpClient(IPEndPoint) .. binds it to the specified local endpoint.

So effectively, with the first constructor a socket is opened on an available, "OS-assigned" local port and then connected to the server, whose address or DNS-name and port are passed in as arguments; after that you're ready to send or receive data.

With the second constructor a socket is just opened on a certain local port (which is identified in the endpoint argument), but that's all - no connection to any [remote, or even local] server is made, because no server info is known yet; you'd need to call one of Connect(.) methods before making any comm operations (similar to the workaround you found).


Why don't you specify the correct IP in the application config?

Only one usage of each socket address (protocol/network address / port) is normally permitted

Means that someone (your or another application) is already listening on that ip/port.


Right now I use an work arround. I create an TcpClient() with an empty constuctor and then I use the Connect(IPendpoint) and this works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜