Skip to content

Instantly share code, notes, and snippets.

@OneOfOne
Created April 22, 2018 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OneOfOne/5368f638f7df1035862659a7bec6ca2f to your computer and use it in GitHub Desktop.
Save OneOfOne/5368f638f7df1035862659a7bec6ca2f to your computer and use it in GitHub Desktop.
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())
}
@OneOfOne
Copy link
Author

OneOfOne commented Dec 3, 2019 via email

@aofei
Copy link

aofei commented Dec 3, 2019

Maybe you can try the following steps (worked on my side), I learned from here:

  1. Created a TUN named tun0
  2. ifconfig tun0 10.2.0.1 pointopoint 10.2.2 netmask 255.255.255.0 mtu 1500 up
  3. iptables -I FORWARD -i tun0 -o eth0 -s 10.2.0.0/24 -m conntrack --ctstate NEW -j ACCEPT
  4. iptables -I FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  5. iptables -t nat -I POSTROUTING -o eth0 -s 10.2.0.0/24 -j MASQUERADE

I just wrote a VPN (Tunneling over WebSocket) and it finally worked today. Its server is written in Go, and its client is an iOS app.

@OneOfOne
Copy link
Author

OneOfOne commented Dec 3, 2019 via email

@aofei
Copy link

aofei commented Dec 3, 2019

Of course, there's nothing confidential. I can simplify the server code and send it to you, but you have to wait a few hours because I'm busy with something else now. 😊

@aofei
Copy link

aofei commented Dec 4, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment