0

I need to write a Java program that can catch UDP packets. I wrote a basic UDP Receiver program but I am unsure how to adjust it for this purpose.

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

public class BasicReceiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new BasicReceiver().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
                InetAddress IPAddress = receivePacket.getAddress();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                        IPAddress, receivePacket.getPort());
                serverSocket.send(sendPacket);
            }
        } catch (IOException e) {
            System.out.println(e);
        }
        // should close serverSocket in finally block
    }
}

I am not receiving any packets but I can see packets on my Ethernet Port: WireShark Snapshot

mustaccio
  • 18,234
  • 16
  • 48
  • 57
  • Take a look at the Javadoc for [DatagramSocket::receive](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/net/DatagramSocket.html#receive(java.net.DatagramPacket)): _This method blocks until a datagram is received._ So, the program will not advance past that line of code. No data will be sent. A more typical way to send and receive data like this is to use two separate applications - a server to do the sending and a client to to the receiving. (I suspect what you see on wireshark may be something different.) – andrewJames Apr 03 '20 at 13:14
  • [here is an example how you should receive muticast datagrams](https://stackoverflow.com/a/4405143/12396017) – Maxim Sagaydachny Apr 03 '20 at 13:21

0 Answers0