英文:
running ip4 server on a Mac
问题
我正在使用 Jan Newmarch 的《Go 编程》一书中的一些代码在我的 Mac 上运行一个白天服务器。它使用了以下代码:
func main() {
service := ":1200"
tcpAddr, err := net.ResolveTCPAddr("ip4", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
}
然而,当我运行它时(在 Mac 上),我得到了以下错误:
Fatal error: unknown network ip4
在这段代码中,除了 "ip4" 之外,还有其他可以避免这个错误的选项吗?
注意,我也尝试了 "ip6",但是得到了相同的错误。
英文:
I'm using some code from Jan Newmarch's book on Go to run a daytime server on my mac. It uses this code
func main() {
service := ":1200"
tcpAddr, err := net.ResolveTCPAddr("ip4", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
however, when I run it (on a Mac), I get this error
Fatal error: unknown network ip4
Is there anything other than ip4 that I can include in this code to avoid that error?
tcpAddr, err := net.ResolveTCPAddr("ip4", service)
Note, I also tried ip6
and got the same error.
答案1
得分: 4
根据ResolveTCPAddr
的文档,net
参数的有效值只有"tcp"、"tcp4"和"tcp6"。
我怀疑你可能混淆了ResolveTCPAddr
和ResolveIPAddr
。
英文:
According to the documentation for ResolveTCPAddr
the only valid values for the net
arg are "tcp", "tcp4" and "tcp6"
I suspect you're getting mixed up between ResolveTCPAddr
and ResolveIPAddr
答案2
得分: 1
"ip4" 不是 ResolveTCPAddr 的有效网络 (来源)。
使用 ResolveIPAddr 来解析通用的 IP 地址。
英文:
"ip4" isn't a valid network for ResolveTCPAddr (source).
Use ResolveIPAddr for resolving a general IP address.
答案3
得分: 1
"ip4" 不是一个有效的字符串
请参阅 ResolveTCPAddr 的文档
ResolveTCPAddr 将 addr 解析为形式为 "host:port" 或 "[ipv6-host%zone]:port" 的 TCP 地址,并在网络 net 上解析域名和端口名的一对,net 必须是 "tcp"、"tcp4" 或 "tcp6"。对于 IPv6 的文字地址或主机名必须用方括号括起来,例如 "[::1]:80"、"[ipv6-host]:http" 或 "[ipv6-host%zone]:80"。
代码如下:
func ResolveTCPAddr(net, addr string) (*TCPAddr, error) {
switch net {
case "tcp", "tcp4", "tcp6":
case "": // Go 1.0 未记录的行为的提示通配符
net = "tcp"
default:
return nil, UnknownNetworkError(net)
}
a, err := resolveInternetAddr(net, addr, noDeadline)
if err != nil {
return nil, err
}
return a.toAddr().(*TCPAddr), nil
}
英文:
"ip4" is not a valid string
See the Documentation for ResolveTCPAddr
> ResolveTCPAddr parses addr as a TCP address of the form "host:port" or
> "[ipv6-host%zone]:port" and resolves a pair of domain name and port
> name on the network net, which must be "tcp", "tcp4" or "tcp6". A
> literal address or host name for IPv6 must be enclosed in square
> brackets, as in "[::1]:80", "[ipv6-host]:http" or
> "[ipv6-host%zone]:80".
And the code:
func ResolveTCPAddr(net, addr string) (*TCPAddr, error) {
switch net {
case "tcp", "tcp4", "tcp6":
case "": // a hint wildcard for Go 1.0 undocumented behavior
net = "tcp"
default:
return nil, UnknownNetworkError(net)
}
a, err := resolveInternetAddr(net, addr, noDeadline)
if err != nil {
return nil, err
}
return a.toAddr().(*TCPAddr), nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论