]> git.ipfire.org Git - thirdparty/gcc.git/blob - libgo/go/net/port.go
Add Go frontend, libgo library, and Go testsuite.
[thirdparty/gcc.git] / libgo / go / net / port.go
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 // Read system port mappings from /etc/services
6
7 package net
8
9 import (
10 "os"
11 "sync"
12 )
13
14 var services map[string]map[string]int
15 var servicesError os.Error
16 var onceReadServices sync.Once
17
18 func readServices() {
19 services = make(map[string]map[string]int)
20 var file *file
21 file, servicesError = open("/etc/services")
22 for line, ok := file.readLine(); ok; line, ok = file.readLine() {
23 // "http 80/tcp www www-http # World Wide Web HTTP"
24 if i := byteIndex(line, '#'); i >= 0 {
25 line = line[0:i]
26 }
27 f := getFields(line)
28 if len(f) < 2 {
29 continue
30 }
31 portnet := f[1] // "tcp/80"
32 port, j, ok := dtoi(portnet, 0)
33 if !ok || port <= 0 || j >= len(portnet) || portnet[j] != '/' {
34 continue
35 }
36 netw := portnet[j+1:] // "tcp"
37 m, ok1 := services[netw]
38 if !ok1 {
39 m = make(map[string]int)
40 services[netw] = m
41 }
42 for i := 0; i < len(f); i++ {
43 if i != 1 { // f[1] was port/net
44 m[f[i]] = port
45 }
46 }
47 }
48 file.close()
49 }
50
51 // LookupPort looks up the port for the given network and service.
52 func LookupPort(network, service string) (port int, err os.Error) {
53 onceReadServices.Do(readServices)
54
55 switch network {
56 case "tcp4", "tcp6":
57 network = "tcp"
58 case "udp4", "udp6":
59 network = "udp"
60 }
61
62 if m, ok := services[network]; ok {
63 if port, ok = m[service]; ok {
64 return
65 }
66 }
67 return 0, &AddrError{"unknown port", network + "/" + service}
68 }