#FEATURE by chzeiher
authorchzeiher
Mon, 12 Nov 2018 16:24:46 +0100
changeset 4764 358345478edc
parent 4763 e3c27719faae
child 4765 62ddeead622b
#FEATURE by chzeiher class: Socket class: Socket class added: #getRandomAvailablePortOnHost: Method to return free portnumber as String utilizing TCP Port Assassination to quickly reuse (only works from same host-context).
Socket.st
--- a/Socket.st	Mon Nov 12 14:48:54 2018 +0100
+++ b/Socket.st	Mon Nov 12 16:24:46 2018 +0100
@@ -1424,6 +1424,22 @@
 
 !Socket class methodsFor:'queries'!
 
+getRandomAvailablePortOnHost:aHostnameOrAdress
+"Attempts binding to port 0 on a specified host, thereby getting assigned a random available port which we return. We then release the socket."
+|socket freePort hostAdress|
+aHostnameOrAdress = nil ifTrue: [ hostAdress := '0.0.0.0' ] ifFalse: [ hostAdress := aHostnameOrAdress ].
+socket := Socket newTCP.
+socket bindTo:0 address:hostAdress reuseAddress:true.
+    freePort := socket port.
+socket abortAndClose.
+^freePort                          
+
+
+
+
+
+!
+
 peerFromDomain:domain name:peerName port:port
     |addrClass|