我正在使用 go 創(chuàng)建一個(gè)命令行應(yīng)用程序,該應(yīng)用程序嘗試 ping 給定的主機(jī)/IP 地址。我在主函數(shù)中使用了以下代碼,并在外部進(jìn)行了必要的導(dǎo)入/變量聲明。package mainimport ( "flag" "fmt" "net" "os" "time" "golang.org/x/net/icmp" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6")var icmpType icmp.Typevar isIPv4 = falsevar conn *icmp.PacketConn = nilvar start time.Timevar num intvar sequence intfunc throwError(err error) { fmt.Println(err) os.Exit(1)}func main() { host := "google.com" ttl := 64 ipaddr, err := net.ResolveIPAddr("ip", host) if err != nil { throwError(err) } fmt.Println("The host is", host) fmt.Println("Address of processing is", ipaddr) if ipaddr.IP.To4() != nil { conn, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { throwError(err) } conn.IPv4PacketConn().SetTTL(ttl) isIPv4 = true icmpType = ipv4.ICMPTypeEcho } else { conn, err := icmp.ListenPacket("ip6:ipv6-icmp", "::") if err != nil { throwError(err) } conn.IPv6PacketConn().SetHopLimit(ttl) icmpType = ipv6.ICMPTypeEchoRequest } fmt.Println("isipv4", isIPv4) msg := icmp.Message{ Type: icmpType, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: 0, Data: []byte(""), }, } msgBytes, err := msg.Marshal(nil) if err != nil { fmt.Println(err) } _, err = conn.WriteTo(msgBytes, ipaddr) if err != nil { // error occurs inside this block fmt.Println(err) }}具體來說,據(jù)我所知,錯(cuò)誤發(fā)生在我調(diào)用該conn.WriteTo函數(shù)之后。錯(cuò)誤信息是invalid connection任何幫助,將不勝感激。謝謝!
2 回答

慕哥6287543
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
無效連接可能是由于您以非特權(quán)方式運(yùn)行程序所致。使用 'ip4:icmp' 和 net.IPAddr 僅在您以特權(quán)模式運(yùn)行程序時(shí)才有效,例如使用 sudo。如果你想使用非特權(quán)的 ListenPacket,你不能使用 'ip4:icmp' 作為網(wǎng)絡(luò),而是使用 'upd4',參見https://godoc.org/golang.org/x/net/icmp#ListenPacket。如果您在 ListenPacket 中使用“udp4”作為網(wǎng)絡(luò),您的 WriteTo 必須使用 net.UDPAddr 而不是 net.IPAddr。
像這樣: https: //play.golang.org/p/qnxOYbVgk26

人到中年有點(diǎn)甜
TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
也許替換你所有的
throwError(err)
和
fmt.Errorf("Error information: %s", err.Error())
有關(guān)錯(cuò)誤發(fā)生的確切位置/原因的更多信息。
- 2 回答
- 0 關(guān)注
- 143 瀏覽
添加回答
舉報(bào)
0/150
提交
取消