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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses
Course of the Month9 days, 3 hours left to enroll

764 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