Home » Core Java » net » DatagramPacket » Send network DatagramPacket

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Send network DatagramPacket

This is an example of how to send a Datagram packet over the network in Java. Sending Datagram packets between two hosts in Java implies that you should :

  • Retrieve the Address object of the target host. This object contains all address related information about the specific host
  • Create a DatagramPacket Object providing the actual data to be send, the data length, the destination address and port
  • Create a DatagramSocket Object to send the packet created previously
  • Use the send(DatagramPacket) API method of the DatagramSocket Object to send the actual DatagramPacket over the network

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.InetAddress;
import java.net.SocketException;

public class SendNetworkDatagramPacket {
	
	public static void main(String[] args) {
		
		try {
			
			byte[] data = { 0x1, 0x2 };
			
			InetAddress addr = InetAddress.getByName("myhost");
			int port = 1234;
			
			DatagramPacket request = new DatagramPacket(data, data.length, addr, port);
	
  DatagramSocket socket = new DatagramSocket();
	
  socket.send(request);
		    
		} 
		catch (SocketException se) {
			se.printStackTrace();
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
		
	}

}

This was an example of how to send 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