I have a server with many IP addresses, and a UDP socket bound to 0.0.0.0 so I can receive UDP from any of them. How can I specify the source IP address to use in the UDP packets I am sending? My current implementation is using NIO so maybe using the DatagramChannel to perform the sending is the problem.
The following program demonstrates that your requirement is imaginary. It shows that a datagram packet originated at a DatagramSocket
bound to 0.0.0.0 is delivered with a source-address of 127.0.0.1.
public static void main(String[] args) throws IOException
{
DatagramSocket ds1 = new DatagramSocket(0);
int port = ds1.getLocalPort();
System.out.println(ds1.getLocalAddress());
DatagramSocket ds2 = new DatagramSocket();
byte[] bytes = {0x01};
SocketAddress sa = new InetSocketAddress("localhost", port);
DatagramPacket dp = new DatagramPacket(bytes, 0, bytes.length, sa);
ds2.send(dp);
ds1.receive(dp);
ds2.send(dp);
ds2.receive(dp);
System.out.println(dp.getAddress());
}
我放弃了一个干净的解决方案,只对服务器上的每个IP地址使用一个绑定的DatagramSocket,该地址可用于发送UDP以及出站数据包的特定源IP。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.