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

通过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)
    }
}
  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容