Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending and receiving UDP packets?

Tags:

java

firewall

udp

I have made a program to send an UDP packets from a client to a server.

Here is the transmitter code:

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

public class JavaApplication9 {    
    public static void main(String[] args) throws UnknownHostException, SocketException, IOException  {
        // TODO code application logic here
        byte[] buffer = {10,23,12,31,43,32,24};
        byte [] IP = {-64,-88,1,106};
        InetAddress address = InetAddress.getByAddress(IP);
        DatagramPacket packet = new DatagramPacket(
                buffer, buffer.length, address, 57
                );
        DatagramSocket datagramSocket = new DatagramSocket();
        datagramSocket.send(packet);
        System.out.println(InetAddress.getLocalHost().getHostAddress());
    }
}

The receiver code function is this:

public void run() {
    try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        byte[] sendData = new byte[8];

        while (true) {
              DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData());
              System.out.println("RECEIVED: " + sentence);
              InetAddress IPAddress = receivePacket.getAddress();
              String sendString = "polo";
              sendData = sendString.getBytes();
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
              serverSocket.send(sendPacket);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I have used the Wireshark program. The UDP packet is received in the Wireshark program at the receiver but the Java program wouldn't recognize it, the program just keeps listening to the port and nothing happens?

like image 227
Amro Raed El Maadawi Avatar asked May 11 '12 18:05

Amro Raed El Maadawi


People also ask

How do you send and receive UDP packets?

To receive packets from all the sending hosts, specify the remote IP address as 0.0. 0.0 . Match the port number specified in the Local IP Port parameter with the remote port number of the sending host. You can choose to receive the UDP packets in blocking or non-blocking mode.

What is UDP send receive?

Send/Receive allows you to send UDP datagrams and if selected, to listen for a response bound to the port on local host. Receive only listens indefinitely for UDP packets and outputs the result in the log section.

Can I send and receive UDP from same port?

Once connected, a TCP socket can only send and receive to/from the remote machine. This means that you'll need one TCP socket for each client in your application. UDP is not connection-based, you can send and receive to/from anyone at any time with the same socket.

Does UDP send a response packet?

UDP is completely stateless, so after firing off a packet the only way an application can expect a response is if it knows the other end is going to send one.


1 Answers

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging, try listening on port > 1024 (e.g. 5000 or 9000). Ports < 1024 are normally used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check to prevent such a situation.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

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

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}
like image 118
CodeMonkey Avatar answered Oct 31 '22 21:10

CodeMonkey