C# – Controlling which Network Card TCP/IP message are sent on


The system I'm currently working on consists of a controller PC running XP with .Net 2 connected to a set of embedded systems. All these components communicate with each other over an ethernet network. I'm currently using TcpClient.Connect on the XP computer to open a connection to the embedded systems to send TCP/IP messages.

I now have to connect the XP computer to an external network to send processing data to, so there are now two network cards on the XP computer. However, the messages sent to the external network mustn't appear on the network connecting the embedded systems together (don't want to consume the bandwidth) and the messages to the embedded systems mustn't appear on the external network.

So, the assertion I'm making is that messages sent to a defined IP address are sent out on both network cards when using the TcpClient.Connect method.

How do I specify which physical network card messages are sent via, ideally using the .Net networking API. If no such method exists in .Net, then I can always P/Invoke the Win32 API.


Best Solution

Try using a Socket for your client instead of the TcpClient Class.

Then you can use Socket.Bind to target your local network adapter

    int port = 1234;

    IPHostEntry entry = Dns.GetHostEntry(Dns.GetHostName());

    //find ip address for your adapter here
    IPAddress localAddress = entry.AddressList.FirstOrDefault();

    IPEndPoint localEndPoint = new IPEndPoint(localAddress, port);

    //use socket instead of a TcpClient
    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    //binds client to the local end point


Related Question