Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2014
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "log"
  6. "net"
  7. "time"
  8. "syscall"
  9. )
  10.  
  11.  
  12. type mystruct struct {
  13. myconn *net.UDPConn
  14. }
  15.  
  16. func bindToInterface(conn net.PacketConn, iface string) {
  17. file, err := conn.(*net.UDPConn).File()
  18. if err != nil {
  19. log.Fatal("Could not bind to interface ", iface)
  20. }
  21. fd := file.Fd()
  22. syscall.BindToDevice(int(fd), iface)
  23. }
  24.  
  25.  
  26. func manageUDP(structure *mystruct) {
  27. buf := make([]byte, 1000)
  28. udpAddr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:9999")
  29. udpConn, err := net.DialUDP("udp", nil, udpAddr)
  30. if err != nil {
  31. log.Fatal(err.Error())
  32. }
  33.  
  34. structure.myconn = udpConn
  35.  
  36. bindToInterface(udpConn, "eth0")
  37.  
  38. for {
  39. n, err := udpConn.Read(buf)
  40. if err != nil {
  41. log.Fatal("FATAL->", err.Error())
  42. } else {
  43. log.Print("Received some data: ", n)
  44. }
  45. }
  46. }
  47.  
  48. func main() {
  49. count := 1
  50. m := &mystruct{}
  51.  
  52. go manageUDP(m)
  53.  
  54. go func() {
  55. c := time.Tick(1 * time.Second)
  56. for now := range c {
  57. fmt.Printf("%v %d\n", now, count)
  58. count += 1
  59. }
  60. }()
  61.  
  62. fmt.Println("Will *normally* timeout after 5 seconds")
  63.  
  64. select {
  65. case <-time.After(5 * time.Second):
  66. fmt.Println("Trying to time out")
  67. m.myconn.SetReadDeadline(time.Now().Add(-1 * time.Second))
  68. }
  69.  
  70. select {}
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement