简体   繁体   English

为什么DatagramSocket的getPort()返回-1?

[英]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.

相关问题 当肯定连接时,为什么Java DatagramSocket在“ isConnected”上返回false? - Why does Java DatagramSocket return false on “isConnected” when it is definitely connected? 在哪种情况下可以在DatagramSocket中使用getPort()? - In which situation can I use getPort() in a DatagramSocket? JAX-WS Service.getPort是否在每次调用时都返回一个新端口? - Does JAX-WS Service.getPort return a new port on each call? Java:为什么DatagramSocket的`receive`方法会截断消息? - Java: why does DatagramSocket's `receive` method truncate messages? 为什么DatagramSocket不通过网络发送多播地址? - Why a DatagramSocket does not send over the network with multicast address? 为什么java.net.DatagramSocket支持“连接”状态? - Why does java.net.DatagramSocket support a “connected” state? 如果端口对多播组无关紧要,为什么DatagramSocket.joinGroup()方法采用SocketAddress? - Why DatagramSocket.joinGroup() method takes a SocketAddress if the port does not matter for a multicast group? DatagramSocket.receive()何时会引发IOException? - When does DatagramSocket.receive() throw IOException? Java UDP DatagramSocket不接收DatagramPacket - Java UDP DatagramSocket does not receive DatagramPacket Android是否为DatagramSocket排队UDP数据包? - Does Android queue UDP packets for DatagramSocket?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM