Send and receive UDP packets

Command to send UDP packets under linux

安装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

Code to send and receive UDP packets

Send packet

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) {
	
}

Receive packets

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) {
	
}

Capture packet

The wireshark tool under Windows captures the
packet through the tcpdump command under Linux

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

Guess you like

Origin www.cnblogs.com/pengsn/p/12712824.html