我有一台有多个网络接口的机器,我正在尝试使用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地址)运行时,程序将按预期运行。
我的所有测试都在Mac上运行10.8.2。