I'm driving myself crazy.
Microsoft provides an awesome way of binding a local network adaptor and port for a new TCPClient by using the constructor:
TcpClient newClient = new TcpClient(IPEndPoint localEP);
Given a general remoteEndPoint, either IPv4 or IPv6, and assuming MANY possible localEPs, there does not seem to be a sensible way of determining which localEP to bind to before then calling:
TcpClient.Connect(IPEndPoint remoteEP)
.net does provide a parameterless TcpClient constructor, which will automatically determine which localEP is best when calling .Connect but unfortunately that does not support IPv6 targets.
My first thought was to access the IP routing table and working out myself which adaptor to use but it seems .net does not provide that functionality either.
I have found a solution which involves a P.Invoke to GetBestInterface() but unfortunately I need to be able to deploy in Mono so really need a managed solution.
My question/problem is: Given a known remoteEP, and a list of all known localEPs how do I correctly choose the correct localEP when instantiating the tcpClient so that the connect method is successful.
If what you're asking is what to use for localEP, you could use new IPEndPoint(IPAddress.Any, myPort) This will bind to any available IP addresses on the local computer and use port myPort. That way something can connect to the computer with whatever IP it likes. If you have multiple IPs (e.g. NICs) it can connect, if i has IPv4 and IPv6, it can connect to either.
e.g. :
var client = new TcpClient(new IPEndPoint(IPAddress.Any, myPort));
But, you can normally just use new TcpClient();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With