Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "log"
- "net"
- "time"
- "syscall"
- )
- type mystruct struct {
- myconn *net.UDPConn
- }
- func bindToInterface(conn net.PacketConn, iface string) {
- file, err := conn.(*net.UDPConn).File()
- if err != nil {
- log.Fatal("Could not bind to interface ", iface)
- }
- fd := file.Fd()
- syscall.BindToDevice(int(fd), iface)
- }
- func manageUDP(structure *mystruct) {
- buf := make([]byte, 1000)
- udpAddr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:9999")
- udpConn, err := net.DialUDP("udp", nil, udpAddr)
- if err != nil {
- log.Fatal(err.Error())
- }
- structure.myconn = udpConn
- bindToInterface(udpConn, "eth0")
- for {
- n, err := udpConn.Read(buf)
- if err != nil {
- log.Fatal("FATAL->", err.Error())
- } else {
- log.Print("Received some data: ", n)
- }
- }
- }
- func main() {
- count := 1
- m := &mystruct{}
- go manageUDP(m)
- go func() {
- c := time.Tick(1 * time.Second)
- for now := range c {
- fmt.Printf("%v %d\n", now, count)
- count += 1
- }
- }()
- fmt.Println("Will *normally* timeout after 5 seconds")
- select {
- case <-time.After(5 * time.Second):
- fmt.Println("Trying to time out")
- m.myconn.SetReadDeadline(time.Now().Add(-1 * time.Second))
- }
- select {}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement