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.