This is actually a Java question and more appropiate for stackoverflow.com.
However, it's worth noting that in general, this technique is common across all programming languages that don't abstract away the socket interface too much from you.
The default way to do this is by specifying the interface or IP within the socket.
You need to pass an InetAddress
to Socket.bind(). You can get an Eumeration
of IP addresses from a specific interface with the following code:
String iface = "venet0:0";
NetworkInterface nif = NetworkInterface.getByName(iface);
Enumeration nifAddresses = nif.getInetAddresses();
while (nifAddresses.hasMoreElements()) {
InetAddress addr = (InetAddress) nifAddresses.nextElement();
System.out.println(addr.getHostAddress());
}
You then need to create your socket with one of these InetAddresses. If you have an InetAddress
object selected called addr
then the following will work
Socket soc = new java.net.Socket();
soc.bind(addr);
soc.connect(new InetSocketAddress(address, port));
This technique works for most programming languages on Linux. You're using bind(2)
with a specific IP to tell the system what IP address and interface you'll be binding to.