java多网卡接收udp组播消息
java接收udp组播消息
在使用java接收udp组播消息时,遇到多网卡接收不到组播的消息,需要绑定本机接收组播消息的ip地址,加入组接收消息。
import java.io.IOException;
import java.net.*;
public class UdpReceiver {
public static void main(String[] args) throws IOException {
// 组播地址
String multicastIp = "224.2.1.1";
// 组播端口号
int multicastPort = 6000;
// 接收组播数据的网卡地址
String localIp = "192.168.1.1";
// TODO:多网卡绑定组播地址配置
MulticastSocket ms = null;
NetworkInterface nic = NetworkInterface.getByInetAddress(InetAddress.getByName(localIp));
ms = new MulticastSocket(multicastPort);
ms.joinGroup(new InetSocketAddress(multicastIp, multicastPort), nic);
byte[] bytes = new byte[33];
int len = bytes.length;
while (true) {
DatagramPacket datagramPacket = new DatagramPacket(bytes, len);
ms.receive(datagramPacket);
byte[] msgData = datagramPacket.getData();
String dataStr = bytesToHexString(msgData);
System.out.println("接收到的组播数据 = " + dataStr);
}
}
/**
* byte数组转换成16进制字符串
*/
public static String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
}