![](/img/trans.png)
[英]How the server knows the port number of the client in which it will use it to send the responses to the client using java programming socket?
[英]How to get the dynamic port number in Java for Socket client
我試圖找出如何獲取 Socket 動態的端口號。
ServerSocket s = new ServerSocket(0);
System.out.println("listening on port: " + s.getLocalPort())
我在 StackOverflow 上找到了這個例子。 它可以工作,但我不需要 ServerSocket。 我需要一個插座:
Socket s = new Socket("http://www.google.at", 8081);
System.out.println("listening on port: " + s.getLocalPort())
我正在用谷歌搜索,但沒有找到解決方案。 也許有人可以幫助我。 我確信有一種方法可以獲取 Socket Dynamic 的端口號。 但是我在 StackOverflow 和 google 上都找不到它。
我已經嘗試過這個:
Socket s = new Socket("http://www.google.at", 0);
System.out.println("listening on port: " + s.getLocalPort())
問候克里斯托夫
您已經找到了解決方案。 Socket.getLocalPort()
獲取Socket
的本地端口。 很奇怪的是。 如果你沒有像這里那樣綁定那個Socket
,或者將它綁定到端口零,本地端口是動態分配的。
new Socket("...", 0)
(a) 是非法的,並且 (b) 將構成連接到動態遠程端口的嘗試,如果合法,則不合法。
為什么需要知道Socket
的本地端口是另一個問題。
NB ServerSockets
監聽。 Sockets
連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.