dongzhou5344 2018-04-22 00:41
浏览 768

如何在Tun / Tap接口上读取TCP数据包?

I'm working on a simple project that listens on a tun interface and modified the packets then re-sends them to the real interface.

I have tried songgao/water, pkg/tuntap and even writing my own based on some C code floating around but no matter what I tried, I can't receive TCP packets (ICMP/UDP works fine).

I feel like i'm missing something extremely obvious but I can't figure it for the life of me...

The code:

package main

import (
    "log"
    "os"
    "os/exec"

    "golang.org/x/net/ipv4"

    "github.com/songgao/water"
)

const (
    // I use TUN interface, so only plain IP packet, no ethernet header + mtu is set to 1300
    BUFFERSIZE = 1600
    MTU        = "1300"
)

func main() {
    iface, err := water.New(water.Config{})
    fatalIf(err)

    log.Printf("tun interface: %s", iface.Name())
    runBin("/bin/ip", "link", "set", "dev", iface.Name(), "mtu", MTU)
    runBin("/bin/ip", "addr", "add", "10.2.0.10/24", "dev", iface.Name())
    runBin("/bin/ip", "link", "set", "dev", iface.Name(), "up")

    buf := make([]byte, BUFFERSIZE)

    for {
        n, err := iface.Read(buf)
        if err != nil {
            log.Fatal(err)
        }

        header, _ := ipv4.ParseHeader(buf[:n])

        log.Printf("isTCP: %v, header: %s", header.Protocol == 6, header)
    }
}

func fatalIf(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func runBin(bin string, args ...string) {
    cmd := exec.Command(bin, args...)
    cmd.Stderr = os.Stderr
    cmd.Stdout = os.Stdout
    cmd.Stdin = os.Stdin
    fatalIf(cmd.Run())
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog