I created a DatagramSocket and called getPort on it, and it always returned -1. In the javadocs, for the empty DatagramSocket constructor, it says that it will attach itself to an available port. I highly doubt my computer is using every port. At which point in the life cycle does it actually get a port number assigned to it?
DatagramSocket.getPort
returns the port to which the socket is connected - ie the port on the other end of the connection, if you've connected the socket.
Since you haven't connected the socket, it returns -1.
To get the port number at your end, use getLocalPort
instead.
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.