最近在项目中使用到了组播(多播),使用过程中,调用joinGroup方法时出现了Error“No such device”,通过查阅资料得知,这是因为设备有多个网卡,使用Multicast过程中未指定网卡,导致无法加入组播Group。
解决方法:调用 joinGroup() 方法时指定网卡设备
Talk is cheap, show me the code. – 鲁迅
话不多说,我们直接上代码,我使用的Java,各位小伙伴可视情况更改自己的代码。
// 获取所有可用网卡列表
private Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// eth0:代表你想使用的网卡,可根据自己情况命名
private NetworkInterface eth0 = null;
while( interfaces.hasMoreElements() ) {
eth0 = interfaces.nextElement();
if( eth0.getName().equals("eth0") ){
break; // 遍历所有网卡设备,找到自己的目标后,break退出
}
}
// IP:组播地址 String格式
// Port:组播端口 int格式
MulticastSocket socket = new MulticastSocket(Port);
InetAddress address = new InetAddress.getByName(IP);
socket.joinGroup( new InetSocketAddress(inetAddress, Port), eth0 ); // 加入组播
以上,如有错误或纰漏,还望指正。