[英]Why does getPort() for DatagramSocket return -1?
I created a DatagramSocket and called getPort on it, and it always returned -1. 我创建了一个DatagramSocket并在其上调用了getPort,它始终返回-1。 In the javadocs, for the empty DatagramSocket constructor, it says that it will attach itself to an available port.
在javadocs中,对于空的DatagramSocket构造函数,它表示它将自身附加到可用端口。 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. DatagramSocket.getPort
返回套接字连接到的端口,即连接 另一端的端口(如果已连接套接字)。
Since you haven't connected the socket, it returns -1. 由于尚未连接套接字,因此它将返回-1。
To get the port number at your end, use getLocalPort
instead. 要获得端口号,请改用
getLocalPort
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.