Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


UDP packet send problem

Posted on 2003-03-07
Medium Priority
Last Modified: 2008-02-01

Hi, I have trouble sending UDP packets with Java. The following Java code doesn't seem to work:

import java.net.*;
import java.io.*;

public class MessageSend

  private void sendMessage(String message)
     try {
       byte [] data = message.getBytes();
       InetAddress addr = InetAddress.getLocalHost();
       DatagramPacket pack = new DatagramPacket(data, data.length, addr, 60001);
       DatagramSocket ds = new DatagramSocket();
       System.out.println("message sent");
     catch (IOException e) {

  public static void main(String [] argv)
       MessageSend temp = new MessageSend();
       temp.sendMessage("STAYING ALIVE");

I've tested if it's a problem on the receiver side, but this code's Perl equivalent sends UDP packets with no problem.

use IO::Socket;

my $sendSocket = IO::Socket::INET->new(PeerPort => 60001,
                           Proto => 'udp', PeerAddr=>'localhost')
       or die "socket: $@";

print("sending one packet\n");
$sendSocket->send("STAYING ALIVE");

Any help is appreciated. Thanks.
Question by:kushcu
LVL 35

Expert Comment

ID: 8087102
Do you get an exception?

Expert Comment

ID: 8087263

I took your code and added a receiver no problem - see if you can find your problem by looking at this (it definitely works):

import java.net.*;
import java.io.*;

public class Foo {

    private void sendMessage( String message ) {
        try {
            byte[] data = message.getBytes();
            InetAddress addr = InetAddress.getLocalHost();
            DatagramPacket pack = new DatagramPacket( data, data.length, addr, 60001 );
            final DatagramSocket socket = new DatagramSocket( 60001 );
            Runnable receiver = new Runnable() {
                public void run() {
                    try {
                        DatagramPacket received = new DatagramPacket( new byte[ 100 ], 100 );
                        socket.receive( received );
                        String s = new String( received.getData() );
                        System.out.println( "received: " + s );
                    catch ( IOException e ) {
                        throw new RuntimeException( "Problem.. " + e.getMessage() );
            Thread thread = new Thread( receiver );
            Thread.sleep( 1000 );
            socket.send( pack );
            System.out.println( "sent" );
        catch ( Exception e ) {
            System.out.println( e );

    public static void main( String[] argv ) {
        Foo temp = new Foo();
        temp.sendMessage( "STAYING ALIVE" );

Author Comment

ID: 8090512
TimYates, no, I don't get an exception.
doddjames, you are actually creating the DatagramSocket with the port number. If I'm not mistaken, the port gets binded with the socket you're creating. However, in my design, that port number is binded with the receiving side. The receiving side is written in Perl.
As far as I know, you don't need to bind a port to send a UDP message. All the necessary info. is already in the packet structure.
I will check that again, but I guess if I try your example, the receiving side (Perl) will give a socket binding error to port 60001 and will die.

Accepted Solution

EshuunDara earned 700 total points
ID: 8168118
try something like this:

// test.java
// usage : java test <server> <port>
// default port is 60001

import java.net.*;
import java.io.*;

public class test {
    public static void main(String[] args) throws IOException {

     int           port           = 60001;
     String          server           = "localhost";    
     String          buf          = "ping";
     int           ERROR           = 1;
     DatagramPacket     packet;
     InetAddress     address;

     // read arguments
     if(args.length == 2) {
          server = args[0];
               port = Integer.parseInt(args[1]);
          catch (Exception e)
               System.out.println("server port = 60001 (default)");
               port = 4245;
     DatagramSocket socket      = new DatagramSocket();
     address = InetAddress.getByName(server);
     packet = new DatagramPacket(buf.getBytes(), buf.length(), address, port);

     System.out.println("Packet sent to " 
               + packet.getAddress() +
               ":" + packet.getPort());


Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses
Course of the Month11 days, 6 hours left to enroll

572 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question