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

huangapple go评论72阅读模式
英文:

Reading TCP packets via raw sockets in GO

问题

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

如果我将协议从TCP更改为ICMP,我将能够接收数据包。为什么我的代码无法读取到TCP数据包呢?

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)
	}
}
英文:

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

得分: 1

这个问题的关键在于OS X是基于BSD的,而BSD不允许你在TCP层面上编程原始套接字。你必须下降到以太网层面才能这样做。

我正在使用pcap库和gopackets来完成这个任务。

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

英文:

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

huangapple
  • 本文由 发表于 2015年3月7日 00:41:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/28903420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定