1 /* 2 * Copyright (C) 2022 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 package com.android.server.net; 17 18 import com.android.net.module.util.Struct; 19 20 import java.util.Arrays; 21 22 /** 23 * The value of bpf interface index map which is used for NetworkStatsService. 24 */ 25 public class InterfaceMapValue extends Struct { 26 private static final int IF_NAME_SIZE = 16; 27 28 @Field(order = 0, type = Type.ByteArray, arraysize = 16) 29 public final byte[] interfaceName; 30 InterfaceMapValue(String iface)31 public InterfaceMapValue(String iface) { 32 // All array bytes after the interface name, if any, must be 0. 33 interfaceName = Arrays.copyOf(iface.getBytes(), IF_NAME_SIZE); 34 } 35 36 /** 37 * Constructor for Struct#parse. Build this struct from byte array of interface name. 38 * 39 * @param ifName Byte array of interface name, length is expected to be IF_NAME_SIZE(16). 40 * If longer or shorter, interface name will be truncated or padded with zeros. 41 * All array bytes after the interface name, if any, must be 0. 42 */ InterfaceMapValue(final byte[] ifName)43 public InterfaceMapValue(final byte[] ifName) { 44 interfaceName = Arrays.copyOf(ifName, IF_NAME_SIZE); 45 } 46 47 /** Returns the length of the null-terminated string. */ strlen(byte[] str)48 private int strlen(byte[] str) { 49 for (int i = 0; i < str.length; ++i) { 50 if (str[i] == '\0') { 51 return i; 52 } 53 } 54 return str.length; 55 } 56 getInterfaceNameString()57 public String getInterfaceNameString() { 58 return new String(interfaceName, 0 /* offset */, strlen(interfaceName)); 59 } 60 } 61