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.net.module.util; 18 19 20 import android.annotation.Nullable; 21 22 import java.net.Inet6Address; 23 import java.net.InetAddress; 24 25 /** 26 * Various utilities used in connectivity code. 27 * @hide 28 */ 29 public final class ConnectivityUtils { ConnectivityUtils()30 private ConnectivityUtils() {} 31 32 33 /** 34 * Return IP address and port in a string format. 35 */ addressAndPortToString(InetAddress address, int port)36 public static String addressAndPortToString(InetAddress address, int port) { 37 return String.format( 38 (address instanceof Inet6Address) ? "[%s]:%d" : "%s:%d", 39 address.getHostAddress(), port); 40 } 41 42 /** 43 * Return true if the provided address is non-null and an IPv6 Unique Local Address (RFC4193). 44 */ isIPv6ULA(@ullable InetAddress addr)45 public static boolean isIPv6ULA(@Nullable InetAddress addr) { 46 return addr instanceof Inet6Address 47 && ((addr.getAddress()[0] & 0xfe) == 0xfc); 48 } 49 50 /** 51 * Returns the {@code int} nearest in value to {@code value}. 52 * 53 * @param value any {@code long} value 54 * @return the same value cast to {@code int} if it is in the range of the {@code int} 55 * type, {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if 56 * it is too small 57 */ saturatedCast(long value)58 public static int saturatedCast(long value) { 59 if (value > Integer.MAX_VALUE) { 60 return Integer.MAX_VALUE; 61 } 62 if (value < Integer.MIN_VALUE) { 63 return Integer.MIN_VALUE; 64 } 65 return (int) value; 66 } 67 } 68