简体   繁体   中英

Java: send repeatedly from same UDP port or specify localport for UDP Socket.send()

Is it possible to either use the same port over multiple socket.send() or specify a port when creating a DatagramSocket? If so how. I am attempting hole-punching and need to listen from the port that is used and I cannot change the port the client is sending from.

try {
        DatagramSocket dSocket = new DatagramSocket();
        InetAddress serverAddr = InetAddress.getByName(TARGETIP)
        int msg_len = currentMsg.length();
        byte[] message = currentMsg.getBytes();
        DatagramPacket dPacket = new DatagramPacket(message,msg_len,serverAddr,3222);
        dSocket.send(dPacket);
        updateConversationHandler.post(new systemUIUpdate("UDP Packet from " + dSocket.getLocalPort()));
}
catch (Exception e){
    e.getMessage();
    e.printStackTrace();
}

Every time this is run via an eventhandler dSocket.getLocalPort() shows a different port.

Yes you can. There are two solutions depending on what you want to do:

  1. If you want to send the packet from a random port but same port everytime, don't close the socket as mentioned in previous answer.

  2. If you even want to choose the port that you which to send from create DatagramSocket as:

    DatagramSocket dSocket = new DatagramSocket(CLIENT_PORT);

Of course it does. You're creating a new socket every time, and never closing it, so the port stays in use, so the new socket gets a new port.

If you want the same port, use the same socket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM