Reputation: 433
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?
Upvotes: 1
Views: 1334
Reputation: 58909
DatagramSocket.getPort
returns the port to which the socket is connected - i.e. 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.
Upvotes: 7