I ran this UDP client program on ubuntu linux 16.04:
package main
import (
"fmt"
"net"
"time"
"strconv"
)
func CheckError(err error) {
if err != nil {
fmt.Println("Error: " , err)
}
}
func main() {
ServerAddr,err := net.ResolveUDPAddr("udp","127.0.0.1:10001")
CheckError(err)
LocalAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
CheckError(err)
Conn, err := net.DialUDP("udp", LocalAddr, ServerAddr)
CheckError(err)
defer Conn.Close()
i := 0
for {
msg := strconv.Itoa(i)
i++
buf := []byte(msg)
_,err := Conn.Write(buf)
if err != nil {
fmt.Println(msg, err)
}
time.Sleep(time.Second * 1)
}
}
It produces this output:
$ go run server.go
1 write udp 127.0.0.1:58703->127.0.0.1:10001: write: connection refused
3 write udp 127.0.0.1:58703->127.0.0.1:10001: write: connection refused
5 write udp 127.0.0.1:58703->127.0.0.1:10001: write: connection refused
But I expected this output instead:
$ go run server.go
1 write udp 127.0.0.1:58703->127.0.0.1:10001: write: connection refused
2 write udp 127.0.0.1:58703->127.0.0.1:10001: write: connection refused
3 write udp 127.0.0.1:58703->127.0.0.1:10001: write: connection refused
4 write udp 127.0.0.1:58703->127.0.0.1:10001: write: connection refused
5 write udp 127.0.0.1:58703->127.0.0.1:10001: write: connection refused
tcpdump says:
15:28:46.453313 IP localhost.47993 > localhost.10001: UDP, length 1
15:28:46.453338 IP localhost > localhost: ICMP localhost udp port 10001 unreachable, length 37
15:28:48.453821 IP localhost.47993 > localhost.10001: UDP, length 1
15:28:48.453852 IP localhost > localhost: ICMP localhost udp port 10001 unreachable, length 37
15:28:50.454242 IP localhost.47993 > localhost.10001: UDP, length 1
15:28:50.454271 IP localhost > localhost: ICMP localhost udp port 10001 unreachable, length 37
Why does this happen every other time conn.Write writes instead of every time? I'm not blaming go, I just want to learn why.