DatagramPacket

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.

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.
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