• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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.settings.testutils.shadow;
18 
19 import static android.system.OsConstants.AF_INET;
20 import static android.system.OsConstants.AF_INET6;
21 
22 import android.system.Os;
23 
24 import org.robolectric.annotation.Implementation;
25 import org.robolectric.annotation.Implements;
26 
27 import java.net.InetAddress;
28 import java.net.UnknownHostException;
29 import java.util.regex.Pattern;
30 
31 @Implements(Os.class)
32 public class ShadowOs {
33     // These are not actually correct, but good enough for the test
34     private static final Pattern IPV4_PATTERN =
35         Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}$");
36     private static final Pattern IPV6_PATTERN =
37         Pattern.compile("^[0-9a-f]{1,4}(:[0-9a-f]{0,4}){0,6}$");
38 
39     private static final byte[] IPV4_BYTES = new byte[4];
40     private static final byte[] IPV6_BYTES = new byte[16];
41 
42     @Implementation
inet_pton(int family, String address)43     protected static InetAddress inet_pton(int family, String address) {
44         if ((AF_INET  == family && IPV4_PATTERN.matcher(address).find()) ||
45             (AF_INET6 == family && IPV6_PATTERN.matcher(address).find())) {
46             try {
47                 return InetAddress.getByAddress((AF_INET == family) ? IPV4_BYTES : IPV6_BYTES);
48             } catch (UnknownHostException uhe) {
49                 // Shouldn't be reached.
50             }
51         }
52         return null;
53     }
54 }
55