Search code examples
javasocketsnetwork-programmingudpserversocket

How to set the port number for the client in udp (client ,server) program in java?


Each time I am running the client the server tells me a different port number. I searched on that and found that when I set the port to zero it looks for an available port, but I changed it to the number I want public static final int MYPORT = 5555; and still getting a new port number each time from the server.

This is the print method:

System.out.printf(" using port %d\n", receivePacket.getPort());

DatagramSocket socket = new DatagramSocket(null);
SocketAddress localBindPoint = new InetSocketAddress(MYPORT); socket.bind(localBindPoint); 
SocketAddress remoteBindPoint = new InetSocketAddress(args[0], Integer.valueOf(args[1]));

Solution

  • I think you missed the point, this piece of code listen on port 5555:

    The istruction packet.getPort() in the following code returns the port number on the remote host to which this datagram is being sent or from which the datagram was received.

      int MYPORT = 5555;
      DatagramSocket dsocket = new DatagramSocket(MYPORT);
      byte[] buffer = new byte[2048];
    
      // Create a packet to receive data into the buffer
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    
      while (true) {
        // Wait to receive a datagram
        dsocket.receive(packet);
    
        // Convert the contents to a string, and display them
        String msg = new String(buffer, 0, packet.getLength());
        System.out.println(packet.getAddress().getHostName() + ": "
            + msg);
    
        // Reset the length of the packet before reusing it.
        packet.setLength(buffer.length);
    
        System.out.printf(" using port %d\n", packet.getPort());
      }
    

    I have double checked locally:

    sudo lsof -iUDP -n -P   | grep 5555
    java      1606        freedev    5u  IPv6 0x9ed7290ce134656f      0t0  UDP *:5555