github.com/containerd/nerdctl@v1.7.7/pkg/portutil/procnet/procnet_linux.go (about)

     1  /*
     2     Copyright The containerd Authors.
     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 procnet
    18  
    19  import (
    20  	"bufio"
    21  	"fmt"
    22  	"os"
    23  )
    24  
    25  const (
    26  	tcpProto  = "tcp"
    27  	udpProto  = "udp"
    28  	tcp6Proto = "tcp6"
    29  	udp6Proto = "udp6"
    30  	// FIXME: The /proc/net/tcp is not recommended by the kernel, FYI https://www.kernel.org/doc/Documentation/networking/proc_net_tcp.txt
    31  	// In the future, we should use netlink instead of /proc/net/tcp
    32  	netTCPStats  = "/proc/net/tcp"
    33  	netUDPStats  = "/proc/net/udp"
    34  	netTCP6Stats = "/proc/net/tcp6"
    35  	netUDP6Stats = "/proc/net/udp6"
    36  )
    37  
    38  func ReadStatsFileData(protocol string) ([]string, error) {
    39  	var fileAddress string
    40  
    41  	if protocol == tcpProto {
    42  		fileAddress = netTCPStats
    43  	} else if protocol == udpProto {
    44  		fileAddress = netUDPStats
    45  	} else if protocol == tcp6Proto {
    46  		fileAddress = netTCP6Stats
    47  	} else if protocol == udp6Proto {
    48  		fileAddress = netUDP6Stats
    49  	} else {
    50  		return nil, fmt.Errorf("unknown protocol %s", protocol)
    51  	}
    52  
    53  	fp, err := os.Open(fileAddress)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  	defer fp.Close()
    58  	var lines []string
    59  	sc := bufio.NewScanner(fp)
    60  
    61  	for i := 0; sc.Scan(); i++ {
    62  		if i == 0 {
    63  			continue
    64  		}
    65  		lines = append(lines, sc.Text())
    66  	}
    67  
    68  	return lines, nil
    69  }