dongmacheng3222
2015-03-06 16:41
浏览 565
已采纳

通过GO中的原始套接字读取TCP数据包

I'm researching raw sockets in GO. I would like to be able to read all TCP packets going to my computer (OSX, en0: 192.168.1.65)

If I switch the protocol from tcp to icmp, I will get packets. Why do I have no packets being read with my code?

package main

import (
"fmt"
"net"
)

func main() {

    netaddr, err := net.ResolveIPAddr("ip4", "192.168.1.65")
    if err != nil {
        fmt.Println(err)
    }

    conn, err := net.ListenIP("ip4:tcp", netaddr)
    if err != nil {
        fmt.Println(err)
    }

    buf := make([]byte, 2048)
    for {
        numRead, recvAddr, err := conn.ReadFrom(buf)
        if err != nil {
            fmt.Println(err)
        }
        if recvAddr != nil {
            fmt.Println(recvAddr)
        }
        s := string(buf[:numRead])
        fmt.Println(s)
    }
}

图片转代码服务由CSDN问答提供 功能建议

我正在GO中研究原始套接字。 我希望能够读取所有发送到计算机的TCP数据包(OSX,en0:192.168.1.65)

如果我将协议从tcp切换到icmp,我将获得数据包。 为什么我的代码没有读取任何数据包?

 包main 
 
import(
“ fmt” 
“ net” 
)
 
func  main(){
 
 netaddr,err:= net.ResolveIPAddr(“ ip4”,“ 192.168.1.65”)
如果err!= nil {
 fmt.Println(err)
} 
 
  conn,err:= net.ListenIP(“ ip4:tcp”,netaddr)
如果err!= nil {
 fmt.Println(err)
} 
 
 buf:= make([] byte,2048  )
 for {
 numRead,recvAddr,err:= conn.ReadFrom(buf)
 if err!= nil {
 fmt.Println(err)
} 
 if recvAddr!= nil {
 fmt  .Println(recvAddr)
} 
s:=字符串(buf [:numRead])
 fmt.Println(s)
} 
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duannong1801 2015-03-16 17:33
    已采纳

    The problem with this is that OS X is based on BSD, and BSD doesn't allow you to program raw sockets at the TCP level. You have to use go down to the Ethernet level in order to do so.

    I'm using the pcap library with gopackets to do the job.

    https://godoc.org/code.google.com/p/gopacket/pcap

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题