Home » Core Java » net » DatagramPacket » Receive network DatagramPacket

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

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