port_unix.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // +build darwin dragonfly freebsd linux netbsd openbsd solaris
  5. // Read system port mappings from /etc/services
  6. package net
  7. import "sync"
  8. // services contains minimal mappings between services names and port
  9. // numbers for platforms that don't have a complete list of port numbers
  10. // (some Solaris distros).
  11. var services = map[string]map[string]int{
  12. "tcp": {"http": 80},
  13. }
  14. var servicesError error
  15. var onceReadServices sync.Once
  16. func readServices() {
  17. var file *file
  18. if file, servicesError = open("/etc/services"); servicesError != nil {
  19. return
  20. }
  21. for line, ok := file.readLine(); ok; line, ok = file.readLine() {
  22. // "http 80/tcp www www-http # World Wide Web HTTP"
  23. if i := byteIndex(line, '#'); i >= 0 {
  24. line = line[0:i]
  25. }
  26. f := getFields(line)
  27. if len(f) < 2 {
  28. continue
  29. }
  30. portnet := f[1] // "80/tcp"
  31. port, j, ok := dtoi(portnet, 0)
  32. if !ok || port <= 0 || j >= len(portnet) || portnet[j] != '/' {
  33. continue
  34. }
  35. netw := portnet[j+1:] // "tcp"
  36. m, ok1 := services[netw]
  37. if !ok1 {
  38. m = make(map[string]int)
  39. services[netw] = m
  40. }
  41. for i := 0; i < len(f); i++ {
  42. if i != 1 { // f[1] was port/net
  43. m[f[i]] = port
  44. }
  45. }
  46. }
  47. file.close()
  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. switch network {
  53. case "tcp4", "tcp6":
  54. network = "tcp"
  55. case "udp4", "udp6":
  56. network = "udp"
  57. }
  58. if m, ok := services[network]; ok {
  59. if port, ok = m[service]; ok {
  60. return
  61. }
  62. }
  63. return 0, &AddrError{"unknown port", network + "/" + service}
  64. }