3

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)
    }
}
Jonathan Eustace
  • 2,469
  • 12
  • 31
  • 54
  • 2
    Check the errors and see if they say anything first. If you have and there are no errors, just update your code sample to reflect it--folks are more likely to answer if you do. – twotwotwo Mar 06 '15 at 20:21
  • Just from searching around, [I don't think Go actually does raw sockets natively](http://stackoverflow.com/questions/18427655/use-raw-sockets-in-go). For slightly-lower-level-than-normal network access, there is [`ipv4`](http://stackoverflow.com/questions/21320305/raw-socket-sniffing-in-golang) (and an equivalent `ipv6`). There are, apparently, efforts to [use pcap with Go](http://godoc.org/code.google.com/p/gopacket) (via the last answer to the previous question). Not an expert in this area, just searching around for stuff that might help you. – twotwotwo Mar 06 '15 at 20:28
  • Thank you, I just did that. :) – Jonathan Eustace Mar 06 '15 at 21:25
  • It seems that the exact same code does what I want it to running on Fedora 21. But on OSX it doesn't output anything that is UDP or TCP. – Jonathan Eustace Mar 07 '15 at 15:12

1 Answers1

1

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

Jonathan Eustace
  • 2,469
  • 12
  • 31
  • 54
  • 1
    I agree. Just add a reference: http://www.darkcoding.net/software/raw-sockets-in-go-link-layer/ ```If you have UNIX Network Programmings by Richard Stevens, you might be as confused as I was by section 28.4 which claims “received TCP packets are never passed to a raw socket.” That’s clearly not true. It’s a historic note related to BSD. man 7 raw says “Raw sockets may tap all IP protocols in Linux, even protocols like ICMP or TCP” but “This should not be relied upon in portable programs”``` – liudanking May 15 '16 at 15:20