Sie sind auf Seite 1von 2


Write a UDP client that:

• take two arguments, an IP address and a port number
• The first argument represents an broadcast address
• The second arguments represents the port number used by the server
• The client detects the server IP address using the broadcast address supplied as first argument:
• The client sends a datagram containing "PING" to the broadcast address (eg., port number
• The server receives the datagram and responds with a datagram containing "PONG" directly to the client
(unicast), port number is computed directly from the previous datagram
• The client responds with a datagram containing "PING-PONG" directly to the server which repplyed
• If the client receives any other message than "PONG" it should continue to wait for the right message;

Important: When sending the PING-PONG message, be careful to send it on the socket address from where the
datagram came. See the method getSocketAddress from DatagramPacket class.

Example dialog
client->broadcast PING
server->client PONG
client->server PING-PONG

Server Source

public class Server {

public static void main(String[] args) throws Exception {
// Creating and binding the server socket
DatagramSocket socket=new DatagramSocket(new
InetSocketAddress( InetAddress.getByName(""),7654));
// Creating the request buffer
byte[] requestBuffer = new byte[2048];
// Creating the request datagram
DatagramPacket requestDatagram = new DatagramPacket(requestBuffer,0,requestBuffer.length);
String responseString;
byte[] responseBuffer;
int responseOffset = 0;
int reponseLength;
while (true) {
InetAddress clientAddr = requestDatagram.getAddress();
requestBuffer = requestDatagram.getData();
String request = new String(requestBuffer, 0, requestDatagram.getLength());

if (request.equals("PING")) { // Send Pong back

System.out.println("PING <- " + clientAddr.getHostAddress());
responseString = "PONG";
responseBuffer = responseString.getBytes();
reponseLength = responseString.length();

DatagramPacket responseDatagram=new DatagramPacket(responseBuffer,responseOffset,reponseLength);


System.out.println("PONG -> " + clientAddr.getHostAddress());

} else if (request.startsWith("PING-PONG")) {
System.out.println("ESTABLISHED <-> " + clientAddr.getHostAddress());