2008-12-18 16:42:39 -07:00
|
|
|
// 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 (
|
|
|
|
"once";
|
|
|
|
"os";
|
|
|
|
)
|
|
|
|
|
2009-11-05 00:16:46 -07:00
|
|
|
var services map[string]map[string]int
|
2009-04-17 01:08:24 -06:00
|
|
|
var servicesError os.Error
|
2008-12-18 16:42:39 -07:00
|
|
|
|
2009-02-15 15:18:39 -07:00
|
|
|
func readServices() {
|
2009-11-05 00:16:46 -07:00
|
|
|
services = make(map[string]map[string]int);
|
2009-03-05 16:48:12 -07:00
|
|
|
var file *file;
|
|
|
|
file, servicesError = open("/etc/services");
|
2009-02-15 15:18:39 -07:00
|
|
|
for line, ok := file.readLine(); ok; line, ok = file.readLine() {
|
2008-12-18 16:42:39 -07:00
|
|
|
// "http 80/tcp www www-http # World Wide Web HTTP"
|
2009-02-15 15:18:39 -07:00
|
|
|
if i := byteIndex(line, '#'); i >= 0 {
|
2008-12-18 16:42:39 -07:00
|
|
|
line = line[0:i];
|
|
|
|
}
|
2009-02-15 15:18:39 -07:00
|
|
|
f := getFields(line);
|
2008-12-18 16:42:39 -07:00
|
|
|
if len(f) < 2 {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
portnet := f[1]; // "tcp/80"
|
2009-02-15 15:18:39 -07:00
|
|
|
port, j, ok := dtoi(portnet, 0);
|
2008-12-18 16:42:39 -07:00
|
|
|
if !ok || port <= 0 || j >= len(portnet) || portnet[j] != '/' {
|
2009-11-05 00:16:46 -07:00
|
|
|
continue;
|
2008-12-18 16:42:39 -07:00
|
|
|
}
|
2009-11-05 00:16:46 -07:00
|
|
|
netw := portnet[j+1 : len(portnet)]; // "tcp"
|
2008-12-18 16:42:39 -07:00
|
|
|
m, ok1 := services[netw];
|
|
|
|
if !ok1 {
|
2009-11-05 00:16:46 -07:00
|
|
|
m = make(map[string]int);
|
2008-12-18 16:42:39 -07:00
|
|
|
services[netw] = m;
|
|
|
|
}
|
|
|
|
for i := 0; i < len(f); i++ {
|
|
|
|
if i != 1 { // f[1] was port/net
|
|
|
|
m[f[i]] = port;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2009-02-15 15:18:39 -07:00
|
|
|
file.close();
|
2008-12-18 16:42:39 -07:00
|
|
|
}
|
|
|
|
|
2009-03-05 16:48:12 -07:00
|
|
|
// LookupPort looks up the port for the given network and service.
|
2009-04-17 01:08:24 -06:00
|
|
|
func LookupPort(network, service string) (port int, err os.Error) {
|
2009-02-15 15:18:39 -07:00
|
|
|
once.Do(readServices);
|
2008-12-18 16:42:39 -07:00
|
|
|
|
2009-03-05 16:48:12 -07:00
|
|
|
switch network {
|
2008-12-18 16:42:39 -07:00
|
|
|
case "tcp4", "tcp6":
|
2009-03-05 16:48:12 -07:00
|
|
|
network = "tcp";
|
2008-12-18 16:42:39 -07:00
|
|
|
case "udp4", "udp6":
|
2009-03-05 16:48:12 -07:00
|
|
|
network = "udp";
|
2008-12-18 16:42:39 -07:00
|
|
|
}
|
|
|
|
|
2009-06-25 21:24:55 -06:00
|
|
|
if m, ok := services[network]; ok {
|
|
|
|
if port, ok = m[service]; ok {
|
|
|
|
return;
|
|
|
|
}
|
2008-12-18 16:42:39 -07:00
|
|
|
}
|
2009-11-05 00:16:46 -07:00
|
|
|
return 0, &AddrError{"unknown port", network+"/"+service};
|
2008-12-18 16:42:39 -07:00
|
|
|
}
|