hey,大家好,最近我在看golang基础部分,尝试了《Go语言编程》中关于socket编程,我试验了以下代码,却提示我说Fatal error: dial ip4:icmp 78.216.200.70: socket: operation not permitted,我已经确认ping存在,且已使用chmod将ping权限设置为u+s,我的系统是os x,代码如下:
```
package main
import (
"os"
"fmt"
"net"
"bytes"
"io"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: ", os.Args[0], "host")
os.Exit(1)
}
service := os.Args[1]
conn, err := net.Dial("ip4:icmp", service)
checkError(err)
var msg [512]byte
msg[0] = 8 // echo
msg[1] = 0 // code 0
msg[2] = 0 // checksum
msg[3] = 0 // checksum
msg[4] = 0 // identifier[0]
msg[5] = 13 //identifier[1]
msg[6] = 0 // sequence[0]
msg[7] = 37 // sequence[1]
len := 8
check := checkSum(msg[0:len])
msg[2] = byte(check >> 8)
msg[3] = byte(check & 255)
_, err = conn.Write(msg[0:len])
checkError(err)
_, err = conn.Read(msg[0:])
fmt.Println("Got response")
if msg[5] == 13 {
fmt.Println("Identifier matches")
}
if msg[7] == 37 {
fmt.Println("Sequence matches")
}
os.Exit(0)
}
func checkSum(msg []byte) uint16 {
sum := 0
for n := 1; n < len(msg)-1; n += 2 {
sum += int(msg[n])*256 + int(msg[n+1])
}
sum = (sum >> 16) + (sum & 0xffff)
sum += (sum >> 16)
var answer uint16 = uint16(^sum)
return answer
}
func readFully(conn net.Conn) ([]byte, error) {
defer conn.Close()
result := bytes.NewBuffer(nil)
var buf [512]byte
for {
n, err := conn.Read(buf[0:])
result.Write(buf[0:n])
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
}
return result.Bytes(), nil
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
}
os.Exit(1)
}
```
请问我这个问题出在哪里呢
更多评论
应该不是指你编译出来的这个文件有没有执行权限,而是有没有网络操作权限。
比如你的命令应该改成 `sudo go run main.go` or `sudo ./ping xxx.xxx.xxx.xxx`
#1
If your program uses this package in raw socket mode, it needs to be run as a root user.
#2