11/*
2- * Copyright (c) 2001, 2019 , Oracle and/or its affiliates. All rights reserved.
2+ * Copyright (c) 2001, 2024 , Oracle and/or its affiliates. All rights reserved.
33 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44 *
55 * This code is free software; you can redistribute it and/or modify it
3636import java .util .*;
3737import java .lang .reflect .Field ;
3838
39+ import jdk .test .lib .Platform ;
40+
3941
4042public class AdaptorBasic {
4143
@@ -69,6 +71,8 @@ static void test(DatagramSocket ds, InetSocketAddress dst, boolean shouldTimeout
6971 for (;;) {
7072 try {
7173 ds .receive (ip );
74+ // weed off stray datagrams
75+ if (ip .getPort () != dst .getPort ()) continue ;
7276 } catch (SocketTimeoutException x ) {
7377 if (shouldTimeout ) {
7478 out .println ("Receive timed out, as expected" );
@@ -111,12 +115,36 @@ static void test(InetSocketAddress dst,
111115 // Original
112116 ds = new DatagramSocket ();
113117 } else {
114- DatagramChannel dc = DatagramChannel .open ();
115- ds = dc .socket ();
116- ds .bind (new InetSocketAddress (0 ));
118+ int attempts = 0 ;
119+ DatagramChannel toclose = null ;
120+ while (true ) {
121+ DatagramChannel dc = DatagramChannel .open ();
122+ ds = dc .socket ();
123+ if (Platform .isOSX () && dst .getAddress ().isLoopbackAddress ()) {
124+ // avoid binding to the wildcard on macOS if possible, in order to limit
125+ // potential port conflict issues
126+ ds .bind (new InetSocketAddress (InetAddress .getLoopbackAddress (), 0 ));
127+ } else {
128+ ds .bind (new InetSocketAddress (0 ));
129+ }
130+ // on some systems it may be possible to bind two sockets
131+ // to the same port if one of them is bound to the wildcard,
132+ // if that happens, try again...
133+ if (ds .getLocalPort () == dst .getPort ()) {
134+ if (toclose != null ) toclose .close ();
135+ toclose = dc ;
136+ if (++attempts == 10 ) {
137+ throw new AssertionError ("Couldn't allocate port for client socket" );
138+ }
139+ continue ;
140+ }
141+ if (toclose != null ) toclose .close ();
142+ break ;
143+ }
117144 }
118145
119- out .println ("socket: " + ds );
146+ out .println ("socket: " + ds + " bound to src: "
147+ + ds .getLocalSocketAddress () + ", dst: " + dst );
120148 if (connect ) {
121149 ds .connect (dst );
122150 out .println ("connect: " + ds );
@@ -141,7 +169,7 @@ static void test(InetSocketAddress dst,
141169 public static void main (String [] args ) throws Exception {
142170 // need an UDP echo server
143171 try (TestServers .UdpEchoServer echoServer
144- = TestServers .UdpEchoServer .startNewServer (100 )) {
172+ = TestServers .UdpEchoServer .startNewServer (100 , InetAddress . getLoopbackAddress () )) {
145173 final InetSocketAddress address
146174 = new InetSocketAddress (echoServer .getAddress (),
147175 echoServer .getPort ());
0 commit comments