NewNetAddressString returns a new NetAddress using the provided address in the form of "ID@IP:Port". Also resolves the host if host is not an IP. Errors are of type ErrNetAddressXxx where Xxx is in (NoID, Invalid, Lookup)
(addr string)
| 68 | // Also resolves the host if host is not an IP. |
| 69 | // Errors are of type ErrNetAddressXxx where Xxx is in (NoID, Invalid, Lookup) |
| 70 | func NewNetAddressString(addr string) (*NetAddress, error) { |
| 71 | addrWithoutProtocol := removeProtocolIfDefined(addr) |
| 72 | spl := strings.Split(addrWithoutProtocol, "@") |
| 73 | if len(spl) != 2 { |
| 74 | return nil, ErrNetAddressNoID{addr} |
| 75 | } |
| 76 | |
| 77 | // get ID |
| 78 | if err := validateID(ID(spl[0])); err != nil { |
| 79 | return nil, ErrNetAddressInvalid{addrWithoutProtocol, err} |
| 80 | } |
| 81 | var id ID |
| 82 | id, addrWithoutProtocol = ID(spl[0]), spl[1] |
| 83 | |
| 84 | // get host and port |
| 85 | host, portStr, err := net.SplitHostPort(addrWithoutProtocol) |
| 86 | if err != nil { |
| 87 | return nil, ErrNetAddressInvalid{addrWithoutProtocol, err} |
| 88 | } |
| 89 | if len(host) == 0 { |
| 90 | return nil, ErrNetAddressInvalid{ |
| 91 | addrWithoutProtocol, |
| 92 | errors.New("host is empty")} |
| 93 | } |
| 94 | |
| 95 | ip := net.ParseIP(host) |
| 96 | if ip == nil { |
| 97 | ips, err := net.LookupIP(host) |
| 98 | if err != nil { |
| 99 | return nil, ErrNetAddressLookup{host, err} |
| 100 | } |
| 101 | ip = ips[0] |
| 102 | } |
| 103 | |
| 104 | port, err := strconv.ParseUint(portStr, 10, 16) |
| 105 | if err != nil { |
| 106 | return nil, ErrNetAddressInvalid{portStr, err} |
| 107 | } |
| 108 | |
| 109 | na := NewNetAddressIPPort(ip, uint16(port)) |
| 110 | na.ID = id |
| 111 | return na, nil |
| 112 | } |
| 113 | |
| 114 | // NewNetAddressStrings returns an array of NetAddress'es build using |
| 115 | // the provided strings. |