I try to find out how to get the Portnumber for a Socket dynamic.
ServerSocket s = new ServerSocket(0);
System.out.println("listening on port: " + s.getLocalPort())
I found this example on StackOverflow. It works but I do not need a ServerSocket. I need a Socket:
Socket s = new Socket("http://www.google.at", 8081);
System.out.println("listening on port: " + s.getLocalPort())
I was searching with google and did not find the Solution. Maybe one can help me. I am sure there is a way to get the Portnumber for Socket Dynamic. But I could not find it on StackOverflow and on google.
I already try this one:
Socket s = new Socket("http://www.google.at", 0);
System.out.println("listening on port: " + s.getLocalPort())
greetings Christoph
You have already found the solution. Socket.getLocalPort()
gets you the local port of a Socket
. Strangely enough. If you haven't bound that Socket
, as here, or bound it to port zero, the local port is allocated dynamically.
new Socket("...", 0)
(a) is illegal and (b) would constitute an attempt to connect to a dynamic remote port, if it was legal, which it isn't.
Why you need to know the local port of a Socket
is another question.
NB ServerSockets
listen. Sockets
connect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.