简体   繁体   English

在哪种情况下可以在DatagramSocket中使用getPort()?

[英]In which situation can I use getPort() in a DatagramSocket?

I'm using DatagramSockets to build a application and I stacked in a point of the code that I should identify which port my socket was bound. 我正在使用DatagramSockets来构建应用程序,并且将代码堆叠在一点上,以便确定套接字绑定到的端口。 So in this part of my code: 所以在我的代码的这一部分:

        dnsConnection = new DatagramSocket();

        byte[] date = "\nSend me a available server IP!".getBytes();
        pkg = new DatagramPacket(date, date.length, addr, port);

        status.append("\nTrying to send the message to: " + addr.getHostAddress());

        dnsConnection.send(pkg);
        localPort = dnsConnection.getPort();

        status.append("\nRequest has been sent to: " + addr.getHostAddress());
        status.append("\nthrough the port: " + localPort);

As you can see, I'm trying to get the port in which my socket was bound using the method getPort() . 如您所见,我正在尝试使用getPort()方法获取绑定套接字的端口。 Reading the API, we have this statement: 阅读API,我们有以下语句:

public int getPort() public int getPort()

Returns the port number to which this socket is connected. 返回此套接字连接到的端口号。 Returns -1 if the socket is not connected. 如果未连接套接字,则返回-1。

In this sense I continue to search an alternative and I found the method getLocalPort() and in the API: 从这个意义上讲,我继续寻找替代方法,并在API中找到了方法getLocalPort()

public int getLocalPort() public int getLocalPort()

Returns the port number on the local host to which this socket is bound. 返回此套接字绑定到的本地主机上的端口号。

Then using getLocalPort() I could have gotten the port in which my socket is bind, and I understood that getPort() is probably to get the port that the socket is connected, ie, the port of the host in which I want to send information. 然后使用getLocalPort()可以获取绑定套接字的端口,并且我知道getPort()可能是获取套接字所连接的端口,即我要发送的主机的端口信息。 After all this, grew up a question on my head: 毕竟,长大了一个问题:

As UDP is conectionless, in which moment can I use getPort() to recovery the port in which my socket is connected? 由于UDP是无连接的,因此在哪一刻可以使用getPort()恢复连接套接字的端口?

Maybe I understood wrong and getPort() is not related with the remote host, if I'm wrong please clarify-me. 也许我理解错了,并且getPort()与远程主机无关,如果我错了,请澄清一下。

That is. 那是。 Thanks. 谢谢。 Pablo 巴勃罗

When you call dnsConnection.send(pkg), the DatagramPacket pkg includes information of the IP address of the remote host, and the port number on the remote host. 调用dnsConnection.send(pkg)时,DatagramPacket pkg包含有关远程主机IP地址和远程主机上端口号的信息。 When you later call dnsConnection.getPort(), it just returns the remote port number of the last sent packet, which is local information. 当您以后调用dnsConnection.getPort()时,它仅返回最后发送的数据包的远程端口号,这是本地信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM