Created
September 19, 2010 16:03
-
-
Save glacjay/586863 to your computer and use it in GitHub Desktop.
Reading/Writing Mac's TUN/TAP device using Go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"exec" | |
"log" | |
"os" | |
) | |
func main() { | |
file, err := os.Open("/dev/tun0", os.O_RDWR, 0) | |
if err != nil { | |
log.Exitf("error os.Open(): %v\n", err) | |
} | |
cmd, err := exec.Run("/sbin/ifconfig", | |
[]string{"ifconfig", "tun0", "192.168.7.1", "192.168.7.2", "up"}, | |
nil, ".", 0, 1, 2) | |
if err != nil { | |
log.Exitf("error exec.Run(): %v\n", err) | |
} | |
cmd.Wait(0) | |
for { | |
buf := make([]byte, 2048) | |
read, err := file.Read(buf) | |
if err != nil { | |
log.Exitf("error os.Read(): %v\n", err) | |
} | |
for i := 0; i < 4; i++ { | |
buf[i+12], buf[i+16] = buf[i+16], buf[i+12] | |
} | |
buf[20] = 0 | |
buf[22] = 0 | |
buf[23] = 0 | |
var checksum uint16 | |
for i := 20; i < read; i += 2 { | |
checksum += uint16(buf[i])<<8 + uint16(buf[i+1]) | |
} | |
checksum = ^(checksum + 4) | |
buf[22] = byte(checksum >> 8) | |
buf[23] = byte(checksum & ((1 << 8) - 1)) | |
_, err = file.Write(buf) | |
if err != nil { | |
log.Exitf("error os.Write(): %v\n", err) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment