yemista
yemista

Reputation: 433

Why does getPort() for DatagramSocket return -1?

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

Answers (1)

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

Related Questions