|
| 1 | +//go:build wasip1 && purego |
| 2 | + |
| 3 | +package net |
| 4 | + |
| 5 | +import ( |
| 6 | + "fmt" |
| 7 | + "net" |
| 8 | +) |
| 9 | + |
| 10 | +func init() { |
| 11 | + net.DefaultResolver.Dial = DialContext |
| 12 | +} |
| 13 | + |
| 14 | +func lookupAddr(context, network, address string) (net.Addr, error) { |
| 15 | + switch network { |
| 16 | + case "tcp", "tcp4", "tcp6": |
| 17 | + case "udp", "udp4", "udp6": |
| 18 | + case "unix", "unixgram": |
| 19 | + return &net.UnixAddr{Name: address, Net: network}, nil |
| 20 | + default: |
| 21 | + return nil, fmt.Errorf("not implemented: %s", network) |
| 22 | + } |
| 23 | + host, portstr, err := net.SplitHostPort(address) |
| 24 | + if err != nil { |
| 25 | + return nil, err |
| 26 | + } |
| 27 | + port, err := net.LookupPort(network, portstr) |
| 28 | + if err != nil { |
| 29 | + return nil, err |
| 30 | + } |
| 31 | + if host == "" { |
| 32 | + if context == "listen" { |
| 33 | + switch network { |
| 34 | + case "tcp", "tcp4": |
| 35 | + return &net.TCPAddr{IP: net.IPv4zero, Port: port}, nil |
| 36 | + case "tcp6": |
| 37 | + return &net.TCPAddr{IP: net.IPv6zero, Port: port}, nil |
| 38 | + } |
| 39 | + } |
| 40 | + return nil, fmt.Errorf("invalid address %q for %s", address, context) |
| 41 | + } |
| 42 | + ips, err := net.LookupIP(host) |
| 43 | + if err != nil { |
| 44 | + return nil, err |
| 45 | + } |
| 46 | + if network == "tcp" || network == "tcp4" { |
| 47 | + for _, ip := range ips { |
| 48 | + if len(ip) == net.IPv4len { |
| 49 | + return &net.TCPAddr{IP: ip, Port: port}, nil |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + if network == "tcp" || network == "tcp6" { |
| 54 | + for _, ip := range ips { |
| 55 | + if len(ip) == net.IPv6len { |
| 56 | + return &net.TCPAddr{IP: ip, Port: port}, nil |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + if network == "udp" || network == "udp4" { |
| 61 | + for _, ip := range ips { |
| 62 | + if len(ip) == net.IPv4len { |
| 63 | + return &net.UDPAddr{IP: ip, Port: port}, nil |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + if network == "udp" || network == "udp6" { |
| 68 | + for _, ip := range ips { |
| 69 | + if len(ip) == net.IPv6len { |
| 70 | + return &net.UDPAddr{IP: ip, Port: port}, nil |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + return nil, fmt.Errorf("cannot listen on %q", host) |
| 75 | +} |
0 commit comments