github.com/freddyisaac/sicortex-golang@v0.0.0-20231019035217-e03519e66f60/src/net/port_unix.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build darwin dragonfly freebsd linux netbsd openbsd solaris nacl
     6  
     7  // Read system port mappings from /etc/services
     8  
     9  package net
    10  
    11  import "sync"
    12  
    13  var onceReadServices sync.Once
    14  
    15  func readServices() {
    16  	file, err := open("/etc/services")
    17  	if err != nil {
    18  		return
    19  	}
    20  	for line, ok := file.readLine(); ok; line, ok = file.readLine() {
    21  		// "http 80/tcp www www-http # World Wide Web HTTP"
    22  		if i := byteIndex(line, '#'); i >= 0 {
    23  			line = line[:i]
    24  		}
    25  		f := getFields(line)
    26  		if len(f) < 2 {
    27  			continue
    28  		}
    29  		portnet := f[1] // "80/tcp"
    30  		port, j, ok := dtoi(portnet)
    31  		if !ok || port <= 0 || j >= len(portnet) || portnet[j] != '/' {
    32  			continue
    33  		}
    34  		netw := portnet[j+1:] // "tcp"
    35  		m, ok1 := services[netw]
    36  		if !ok1 {
    37  			m = make(map[string]int)
    38  			services[netw] = m
    39  		}
    40  		for i := 0; i < len(f); i++ {
    41  			if i != 1 { // f[1] was port/net
    42  				m[f[i]] = port
    43  			}
    44  		}
    45  	}
    46  	file.close()
    47  }
    48  
    49  // goLookupPort is the native Go implementation of LookupPort.
    50  func goLookupPort(network, service string) (port int, err error) {
    51  	onceReadServices.Do(readServices)
    52  	return lookupPortMap(network, service)
    53  }