Merge "Minor simplification to IpSecService#bindToRandomPort."

This commit is contained in:
Treehugger Robot
2023-02-08 11:13:09 +00:00
committed by Gerrit Code Review

View File

@@ -1221,16 +1221,16 @@ public class IpSecService extends IIpSecService.Stub {
* and re-binding, during which the system could *technically* hand that port out to someone * and re-binding, during which the system could *technically* hand that port out to someone
* else. * else.
*/ */
private int bindToRandomPort(FileDescriptor sockFd, int family) throws IOException { private int bindToRandomPort(FileDescriptor sockFd, int family, InetAddress localAddr)
final InetAddress any = (family == AF_INET6) ? IN6ADDR_ANY : INADDR_ANY; throws IOException {
for (int i = MAX_PORT_BIND_ATTEMPTS; i > 0; i--) { for (int i = MAX_PORT_BIND_ATTEMPTS; i > 0; i--) {
try { try {
FileDescriptor probeSocket = Os.socket(family, SOCK_DGRAM, IPPROTO_UDP); FileDescriptor probeSocket = Os.socket(family, SOCK_DGRAM, IPPROTO_UDP);
Os.bind(probeSocket, any, 0); Os.bind(probeSocket, localAddr, 0);
int port = ((InetSocketAddress) Os.getsockname(probeSocket)).getPort(); int port = ((InetSocketAddress) Os.getsockname(probeSocket)).getPort();
Os.close(probeSocket); Os.close(probeSocket);
Log.v(TAG, "Binding to port " + port); Log.v(TAG, "Binding to port " + port);
Os.bind(sockFd, any, port); Os.bind(sockFd, localAddr, port);
return port; return port;
} catch (ErrnoException e) { } catch (ErrnoException e) {
// Someone miraculously claimed the port just after we closed probeSocket. // Someone miraculously claimed the port just after we closed probeSocket.
@@ -1322,7 +1322,7 @@ public class IpSecService extends IIpSecService.Stub {
Log.v(TAG, "Binding to port " + port); Log.v(TAG, "Binding to port " + port);
Os.bind(pFd.getFileDescriptor(), localAddr, port); Os.bind(pFd.getFileDescriptor(), localAddr, port);
} else { } else {
port = bindToRandomPort(pFd.getFileDescriptor(), family); port = bindToRandomPort(pFd.getFileDescriptor(), family, localAddr);
} }
userRecord.mEncapSocketRecords.put( userRecord.mEncapSocketRecords.put(