/
tun.go
69 lines (53 loc) · 1.14 KB
/
tun.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"fmt"
"os/exec"
"runtime"
"github.com/songgao/water"
)
type Interface struct {
tun *water.Interface
}
func NewInterface() (*Interface, error) {
iface := &Interface{}
ifconfig := water.Config{
DeviceType: water.TUN,
}
ifconfig.Name = "cframe.0"
ifce, err := water.New(ifconfig)
if err != nil {
return nil, err
}
iface.tun = ifce
return iface, nil
}
func (iface *Interface) Up() error {
switch runtime.GOOS {
case "linux":
out, err := execCmd("ifconfig", []string{iface.tun.Name(), "up"})
if err != nil {
return fmt.Errorf("ifconfig fail: %s %v", out, err)
}
default:
return fmt.Errorf("unsupported: %s %s", runtime.GOOS, runtime.GOARCH)
}
return nil
}
func (iface *Interface) Read() ([]byte, error) {
buf := make([]byte, 2048)
n, err := iface.tun.Read(buf)
if err != nil {
return nil, err
}
return buf[:n], nil
}
func (iface *Interface) Write(buf []byte) (int, error) {
return iface.tun.Write(buf)
}
func (iface *Interface) Close() {
iface.tun.Close()
}
func execCmd(cmd string, args []string) (string, error) {
b, err := exec.Command(cmd, args...).CombinedOutput()
return string(b), err
}