UDP protocol realizes Ping message in ICMP protocol

principle:

To use the UDP protocol to realize the Ping message function in the ICMP protocol, it is necessary to simulate the work flow of the Ping message in the grid layer at the application layer, that is, the client first sends an application layer UDP Ping request message to the server section. After the server program receives the UDP Ping request message, it will return a UDP Ping response message to the client. The client can judge the link status by judging the messages received in the program and related information.

flow chart:

Insert picture here

Write server segment program

Features:

1. Open a specific socket according to the user input parameters, and monitor the socket,
2. Accept the application layer Ping request message sent from the client and print it
3. Reply to the client Ping response message

import java.io.*;
import java.net.*;
import java.nio.channels.NonWritableChannelException;
import java.util.*;
public class PingServer {
    
    
	private static final double LOSS_RATE=0.3;
	private static final int AVERAGE_DELAY=100;
	public static void main(String[] args)throws Exception {
    
    
		if(args.length!=1) {
    
    
			System.out.println("Required arguments:port");
			return;
		}
		int port = Integer.parseInt(args[0]);
		Random random = new Random();
		DatagramSocket socket = new DatagramSocket(port);
		while(true) {
    
    
			DatagramPacket requset=new DatagramPacket(new byte[1024], 1024);
			socket.receive(requset);
			printData(requset);
			if(random.nextDouble()<LOSS_RATE) {
    
    
				System.out.println("Reply not sent");
				continue;
			}
			Thread.sleep((int)(random.nextDouble()*2*AVERAGE_DELAY));
			InetAddress clientHost=requset.getAddress();
			int clientPort = requset.getPort();
			byte[] buf = requset.getData();
			DatagramPacket reply= new DatagramPacket(buf, buf.length,clientHost,clientPort);
			socket.send(reply);
			System.out.println("Reply sent");
		}
	}
	private static void printData(DatagramPacket requset) throws Exception {
    
    
		// TODO Auto-generated method stub
		byte[] buf = requset.getData();
		ByteArrayInputStream bais=new ByteArrayInputStream(buf);
		InputStreamReader isr= new InputStreamReader(bais);
		BufferedReader br=new BufferedReader(isr);
		String line = br.readLine();
		System.out.println("Received from"+ requset.getAddress().getHostAddress()+"."+new String(line));
	}
}

Write the client program

Features

1. Establish a connection with the server to construct a UDP Ping request message
2. Send the request message to the server while waiting for and receiving the response message from the server, and close the socket after sending the Ping command 10 times in a row

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PingClient {
    
    
	public static void main(String[] args)throws Exception {
    
    
		if(args.length==0) {
    
    
			System.out.println("Required argument:Host port");
			return;
		}
		if(args.length==1) {
    
    
			System.out.println("Required argument: port");
			return;
		}
		String host=args[0].toString();
		int port = Integer.parseInt(args[1]);
		DatagramSocket clientSocket = new DatagramSocket();
		clientSocket.setSoTimeout(1000);
		InetAddress IPAddress=InetAddress.getByName(host);
		long sendTime,receiveTime;
		for(int i=0;i<10;i++) {
    
    
			byte[] sendData=new byte[1024];
			byte[] receviceData=new byte[1024];
			Date currentTime=new Date();
			SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String timeStamp= formatter.format(currentTime);
			String pingMessage= "Ping"+"i"+""+timeStamp+""+"\r\n";
			sendData = pingMessage.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,IPAddress,port);
			try {
    
    
				sendTime = System.currentTimeMillis();
				clientSocket.send(sendPacket);
				DatagramPacket receivePacket = new DatagramPacket(receviceData, receviceData.length);
				clientSocket.receive(receivePacket);
				receiveTime =System.currentTimeMillis();
				long latency= receiveTime-sendTime;
				String serverAddress= receivePacket.getAddress().getHostAddress();
				System.out.println("From"+serverAddress + ":"+latency+"ms.");
			}catch(java.net.SocketTimeoutException ex){
    
    
				String reply="No reply";
				System.out.println(reply);
			}
		}
		clientSocket.close();
	}
}
The effect is reproduced:

Find the compiled file corresponding to the java file, enter PowerShell and use the CMD command to execute the corresponding statement:
first develop a port number 80,
Insert picture description here
and then open a PowerShell window to execute ServerClient.java 127.0.0.1 80.
Insert picture description here
At this point, the server part:
Insert picture description here
you're done! ! ! ! ! !

Guess you like

Origin blog.csdn.net/qq_41606378/article/details/106531001