diff options
| author | Russ Cox <rsc@golang.org> | 2008-12-18 15:42:39 -0800 |
|---|---|---|
| committer | Russ Cox <rsc@golang.org> | 2008-12-18 15:42:39 -0800 |
| commit | c4df9e3990cbb1a8e0eb7d52c0ea65441195403d (patch) | |
| tree | 03a7b9e046e2ef76f628fd6ce1863871fbb3a842 /src/lib/net/port.go | |
| parent | fbc8538a295e36d100fa93d0224fa65f224944ff (diff) | |
| download | golang-c4df9e3990cbb1a8e0eb7d52c0ea65441195403d.tar.gz | |
host and port name lookup
R=r,presotto
DELTA=1239 (935 added, 281 deleted, 23 changed)
OCL=21041
CL=21539
Diffstat (limited to 'src/lib/net/port.go')
| -rw-r--r-- | src/lib/net/port.go | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/src/lib/net/port.go b/src/lib/net/port.go new file mode 100644 index 000000000..5ff1e5805 --- /dev/null +++ b/src/lib/net/port.go @@ -0,0 +1,68 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Read system port mappings from /etc/services + +package net + +import ( + "io"; + "net"; + "once"; + "os"; + "strconv"; +) + +var services *map[string] *map[string] int + +func ReadServices() { + services = new(map[string] *map[string] int); + file := Open("/etc/services"); + for line, ok := file.ReadLine(); ok; line, ok = file.ReadLine() { + // "http 80/tcp www www-http # World Wide Web HTTP" + if i := ByteIndex(line, '#'); i >= 0 { + line = line[0:i]; + } + f := GetFields(line); + if len(f) < 2 { + continue; + } + portnet := f[1]; // "tcp/80" + port, j, ok := Dtoi(portnet, 0); + if !ok || port <= 0 || j >= len(portnet) || portnet[j] != '/' { + continue + } + netw := portnet[j+1:len(portnet)]; // "tcp" + m, ok1 := services[netw]; + if !ok1 { + m = new(map[string] int); + services[netw] = m; + } + for i := 0; i < len(f); i++ { + if i != 1 { // f[1] was port/net + m[f[i]] = port; + } + } + } + file.Close(); +} + +export func LookupPort(netw, name string) (port int, ok bool) { + once.Do(&ReadServices); + + switch netw { + case "tcp4", "tcp6": + netw = "tcp"; + case "udp4", "udp6": + netw = "udp"; + } + + m, mok := services[netw]; + if !mok { + return + } + port, ok = m[name]; + return +} + |
