我有一台具有多个网络接口的机器,我正在尝试在其上使用 UDP 多播。我把它归结为这个小小的复制程序。
public class Main {
public static void main(String[] args) throws Exception {
InetAddress local = InetAddress.getByName("127.0.0.1"); // hangs
// InetAddress local = InetAddress.getByName("10.0.0.145"); // finishes
List<NetworkInterface> matchingIfs = new ArrayList<NetworkInterface>();
Enumeration<NetworkInterface> netIfs = NetworkInterface.getNetworkInterfaces();
while( netIfs.hasMoreElements() ) {
NetworkInterface netIf = netIfs.nextElement();
Enumeration<InetAddress> addrs = netIf.getInetAddresses();
while( addrs.hasMoreElements() ) {
InetAddress addr = addrs.nextElement();
if( addr.equals(local) ) {
matchingIfs.add(netIf);
break;
}
}
}
NetworkInterface netIf = matchingIfs.get(0);
InetAddress addr = InetAddress.getByName("233.245.29.143");
int port = 59893;
DatagramPacket sendPack = new DatagramPacket(new byte[1600],1600);
DatagramPacket recvPack = new DatagramPacket(new byte[1600],1600);
System.out.println("Using network interface: " + netIf);
MulticastSocket send = new MulticastSocket();
send.setTimeToLive(127);
send.setNetworkInterface(netIf);
MulticastSocket recv = new MulticastSocket(port);
recv.setNetworkInterface(netIf);
recv.joinGroup(addr);
sendPack.setData("asdfasdf".getBytes());
sendPack.setAddress(addr);
sendPack.setPort(port);
System.out.println("About to send");
send.send(sendPack);
System.out.println("Finished send");
System.out.println("About to recieve");
recv.receive(recvPack);
System.out.println("Finished recieve");
String s = new String(recvPack.getData(), recvPack.getOffset(), recvPack.getLength());
System.out.println(s);
}
}
如果我不调用setNetworkInterface
这个程序会在主机有多个网络接口时挂起。
当与127.0.0.1
程序一起运行时,无论网络接口的数量如何,都会挂起等待接收。
当使用10.0.0.145
(机器 IP 地址)运行时,程序按预期运行。
我所有的测试都是在运行 10.8.2 的 Mac 上进行的。