收发UDP数据包

linux下命令发送UDP数据包

安装nc工具
yum install nc

发送UDP到指定ip port
nc -4u 101.69.229.4 7709

发送udp数据包到指定的ip port
echo "pengsn hello word" |nc -4u 101.69.229.4 1001

代码实现收发UDP数据包

发送数据包

try(DatagramSocket ds = new DatagramSocket()){
	byte[] data = "This is a Message send by UDP.".getBytes("utf-8");
	DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("ip"), port);
	ds.send(dp);
}catch(Exception e) {
	
}

接收数据包

try(DatagramSocket ds = new DatagramSocket(1001)){
	byte[] buf = new byte[1024];
	DatagramPacket dp = new DatagramPacket(buf, buf.length);
	ds.receive(dp);
	String ip = dp.getAddress().getHostAddress();
	System.out.println(ip);
	System.out.println("dd:" + new String(dp.getData(), 0, dp.getLength()));
}catch(Exception e) {
	
}

捕获数据包

windows 下wireshark工具抓取
linux 下通过tcpdump命令抓包

tcpdump -i any -s 0 udp port xx -w save.pcap