NetworkServerUDP: get actual ephemeral socket address
authorTJ <hacker@iam.tj>
Mon, 4 May 2015 15:27:29 +0000 (16:27 +0100)
committerTJ <hacker@iam.tj>
Mon, 4 May 2015 15:27:29 +0000 (16:27 +0100)
During construction of a service requesting an ephemeral port
ensure the services' internal SocketAddress reflects the actual
port allocated by the operating system.

src/uk/ac/ntu/n0521366/wsyd/libs/net/NetworkServerUDP.java

index b514fa8..a6f3fcc 100644 (file)
@@ -104,7 +104,14 @@ public class NetworkServerUDP extends NetworkServerAbstract {
     @Override
     public  void serverOpen() throws SocketException {
         _datagramSocket = new DatagramSocket(_socketAddress.getPort(), _socketAddress.getAddress());
-        _datagramSocket.setSoTimeout(100); // 1/10th second blocking timeout on receive() 
+        _datagramSocket.setSoTimeout(100); // 1/10th second blocking timeout on receive()
+
+        if (_socketAddress.getPort() == Network.PORTS_EPHEMERAL) {
+            // reflect the actual port in use if an ephermal port was requested
+            InetSocketAddress actualSA = (InetSocketAddress)_datagramSocket.getLocalSocketAddress();
+            _socketAddress.setAddress(actualSA.getAddress());
+            _socketAddress.setPort(actualSA.getPort());
+        }
     }
     
     /**