Search code examples
csocketsethernet

Linux: TCP socket programming over multiple ethernet ports


I've been scouring the web to see how I can program to utilize two separate ethernet ports (such as eth0 and eth1) in linux using C/C++

I understand how to use socket() and inet_pton but this seems to be only for a single ethernet port.

The first ethernet port is automatically mapped to 192.168.0.100 and the second is 192.168.0.101


Solution

  • Two part answer.

    1. Normally, you don't have to worry about using multiple ethernet ports explicitly. The kernel automatically takes care of it. Here's how it works. For outgoing packets, the kernel sends the packets out over the appropriate ethernet port depending on the destination IP address. So, if network 10.0.0.0 is reachable via eth0, that's where the packet will be sent out from. And if network 11.0.0.0 is reachable via eth1, that's where the packet will be sent out from. The kernel determines network reachability by the netmask, IP address, and default gateway assigned to an interface (in conjunction with routing tables).
    2. For incoming packets, if you bind to ANY address, then all packets for the port you are listening on are delivered to you. You can also choose to bind to a specific IP address, in which case only the packets addressed to that IP address and port will be delivered to you.