sockets.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package utils
  3. import (
  4. "fmt"
  5. "runtime"
  6. "strconv"
  7. "strings"
  8. "github.com/seancfoley/ipaddress-go/ipaddr"
  9. )
  10. func ParseSocketAddress(spec string) (network string, addr string, err error) {
  11. network, addr, found := strings.Cut(spec, ":")
  12. if !found {
  13. err = fmt.Errorf("Invalid socket address: %s must be prefix by a protocol such as unix:", spec)
  14. return
  15. }
  16. if network == "unix" {
  17. if strings.HasPrefix(addr, "@") && runtime.GOOS != "linux" {
  18. err = fmt.Errorf("Abstract UNIX sockets are only supported on Linux. Cannot use: %s", spec)
  19. }
  20. return
  21. }
  22. if network == "tcp" || network == "tcp6" || network == "tcp4" {
  23. host := ipaddr.NewHostName(addr)
  24. if host.IsAddress() {
  25. network = "ip"
  26. }
  27. return
  28. }
  29. if network == "ip" || network == "ip6" || network == "ip4" {
  30. host := ipaddr.NewHostName(addr)
  31. if !host.IsAddress() {
  32. err = fmt.Errorf("Not a valid IP address: %#v. Cannot use: %s", addr, spec)
  33. }
  34. return
  35. }
  36. if network == "fd" {
  37. fd := -1
  38. if fd, err = strconv.Atoi(addr); err != nil || fd < 0 {
  39. err = fmt.Errorf("Not a valid file descriptor number: %#v. Cannot use: %s", addr, spec)
  40. }
  41. return
  42. }
  43. err = fmt.Errorf("Unknown network type: %#v in socket address: %s", network, spec)
  44. return
  45. }