OK. I know similar questions were asked before, but this is different.
I noticed from responses to similar questions that I can use Socket.bind
to specify a certain network interface for outgoing connections. This page is an official instruction on that.
Now, my machine has two NICs eth0
and eth1
, and the system routing table sets eth0
as the outgoing interface for connecting to a server S
.
Then I tried the following:
Socket so = new Socket();
so.bind(new InetSocketAddress("ip.address.of.eth1", 0));
so.connect(new InetSocketAddress("ip.address.of.S", 80));
I used WireShark to capture the packets, and noticed that the "Source Address" field of IP header was indeed ip.address.of.eth1
. But by checking Ethernet headers, I noticed that the source MAC address is actually the MAC address of eth0
, that is, the packets were actually still sent out via eth0
!
Could anyone help explain why it had this behavior? Is it expected? Thanks a lot!
Yes, Socket and ServerSocket use TCP/IP. The package overview for the java.net package is explicit about this, but it's easy to overlook.
In this article, we'll focus on network interfaces and how to access them programmatically in Java. Simply put, a network interface is the point of interconnection between a device and any of its network connections.
There are two communication protocols that we can use for socket programming: User Datagram Protocol (UDP) and Transfer Control Protocol (TCP).
This is the result of the 'weak end system model'. It's too broad to describe here but it is discussed in RFC 1122.
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