ifattr.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package sockaddr
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. // IfAddr is a union of a SockAddr and a net.Interface.
  7. type IfAddr struct {
  8. SockAddr
  9. net.Interface
  10. }
  11. // Attr returns the named attribute as a string
  12. func (ifAddr IfAddr) Attr(attrName AttrName) (string, error) {
  13. val := IfAddrAttr(ifAddr, attrName)
  14. if val != "" {
  15. return val, nil
  16. }
  17. return Attr(ifAddr.SockAddr, attrName)
  18. }
  19. // Attr returns the named attribute as a string
  20. func Attr(sa SockAddr, attrName AttrName) (string, error) {
  21. switch sockType := sa.Type(); {
  22. case sockType&TypeIP != 0:
  23. ip := *ToIPAddr(sa)
  24. attrVal := IPAddrAttr(ip, attrName)
  25. if attrVal != "" {
  26. return attrVal, nil
  27. }
  28. if sockType == TypeIPv4 {
  29. ipv4 := *ToIPv4Addr(sa)
  30. attrVal := IPv4AddrAttr(ipv4, attrName)
  31. if attrVal != "" {
  32. return attrVal, nil
  33. }
  34. } else if sockType == TypeIPv6 {
  35. ipv6 := *ToIPv6Addr(sa)
  36. attrVal := IPv6AddrAttr(ipv6, attrName)
  37. if attrVal != "" {
  38. return attrVal, nil
  39. }
  40. }
  41. case sockType == TypeUnix:
  42. us := *ToUnixSock(sa)
  43. attrVal := UnixSockAttr(us, attrName)
  44. if attrVal != "" {
  45. return attrVal, nil
  46. }
  47. }
  48. // Non type-specific attributes
  49. switch attrName {
  50. case "string":
  51. return sa.String(), nil
  52. case "type":
  53. return sa.Type().String(), nil
  54. }
  55. return "", fmt.Errorf("unsupported attribute name %q", attrName)
  56. }