1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.internal.net.ipsec.ike.net;
18 
19 import android.net.Network;
20 import android.system.ErrnoException;
21 import android.system.Os;
22 import android.system.OsConstants;
23 
24 import java.io.FileDescriptor;
25 import java.io.IOException;
26 import java.net.InetAddress;
27 import java.net.InetSocketAddress;
28 
29 /**
30  * IkeLocalAddressGenerator generates a local IP address for the given Network using the specified
31  * address family, remote address, and server port number.
32  */
33 public class IkeLocalAddressGenerator {
34     /** Generate and return a local IP address on the specified Network. */
generateLocalAddress( Network network, boolean isIpv4, InetAddress remoteAddress, int serverPort)35     public InetAddress generateLocalAddress(
36             Network network, boolean isIpv4, InetAddress remoteAddress, int serverPort)
37             throws ErrnoException, IOException {
38         FileDescriptor sock =
39                 Os.socket(
40                         isIpv4 ? OsConstants.AF_INET : OsConstants.AF_INET6,
41                         OsConstants.SOCK_DGRAM,
42                         OsConstants.IPPROTO_UDP);
43         network.bindSocket(sock);
44         Os.connect(sock, remoteAddress, serverPort);
45         InetSocketAddress localAddr = (InetSocketAddress) Os.getsockname(sock);
46         Os.close(sock);
47 
48         return localAddr.getAddress();
49     }
50 }
51