DatagramPacket

Receive network DatagramPacket

In this example we shall show you how to receive a Datagram packet in Java. For a host to receive Datagram packets in Java implies that you should :

  • Create a DatagramPacket Object providing a placeholder for the received data – here an empty byte array of the default 256 bytes size
  • Create a DatagramSocket Object to receive the Datagram packet from
  • Use the receive(DatagramPacket) API method of the DatagramSocket Object to wait for the actual DatagramPacket from the network. When this method returns, the DatagramPacket’s buffer is filled with the data received

If the specific host address exists and there is no connectivity issues between the client and the host machines then you should be able to send the DatagramPacket to the specified destination.

package com.javacodegeeks.snippets.core;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class ReceiveNetworkDatagramPacket {
	
	public static void main(String[] args) {
		
		try {
			
			byte[] buf = new byte[256]; // default size
			DatagramSocket socket = new DatagramSocket();

			// Wait for packet
			DatagramPacket packet = new DatagramPacket(buf, buf.length);

			// Receives a datagram packet from this socket. When this method returns,
			// the DatagramPacket's buffer is filled with the data received.
			socket.receive(packet);

			System.out.println("Packet length: " + packet.getLength());
			System.out.println("Data: " + buf);
		    
		} 
		catch (SocketException se) {
			se.printStackTrace();
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
		
	}

}

This was an example of how to receive a Datagram packet over the network in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button