dongmacheng3222
dongmacheng3222
2015-03-06 16:41

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

  • sockets
已采纳

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)
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duannong1801 duannong1801 6年前

    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

    点赞 评论 复制链接分享