Created
July 23, 2021 02:49
-
-
Save masiulaniec/d92ff30ca16e79f0b7bcd77b6fd9257c to your computer and use it in GitHub Desktop.
SetReadBuffer effect on UDP listener
This file contains 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
$ cat > udpbufcap.go << EOF | |
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"net" | |
"os" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
// Listen on UDP. | |
receiver, err := net.ListenUDP("udp", nil) | |
if err != nil { | |
panic(err) | |
} | |
// (maybe) Bump receive buffer. | |
switch os.Args[1] { | |
case "base": | |
fmt.Printf("keep rcvbuf as is\n") | |
case "test": | |
rcvbufMax := readint("/proc/sys/net/core/rmem_max") | |
fmt.Printf("set rcvbuf to %d\n", rcvbufMax) | |
if err := receiver.SetReadBuffer(rcvbufMax); err != nil { | |
panic(err) | |
} | |
} | |
// Send many unique packets. | |
sender, err := net.Dial("udp", receiver.LocalAddr().String()) | |
if err != nil { | |
panic(err) | |
} | |
buf := make([]byte, 1024) | |
for i := 0; i < 10000; i++ { | |
buf = append(buf[:0], fmt.Sprintf("seq=%08d!", i)...) | |
buf = buf[:cap(buf)] | |
if _, err := sender.Write(buf); err != nil { | |
panic(err) | |
} | |
} | |
// Read back as many packets as possible, printing identity of each. | |
buf = make([]byte, cap(buf)) | |
for i := 0; i < 10000; i++ { | |
n, err := receiver.Read(buf) | |
if err != nil { | |
panic(err) | |
} | |
if n != cap(buf) { | |
panic(n) | |
} | |
fmt.Printf("i=%5d buf[:16]=%.16q\n", i, buf) | |
} | |
} | |
func readint(path string) int { | |
buf, err := ioutil.ReadFile(path) | |
if err != nil { | |
panic(err) | |
} | |
n, err := strconv.ParseInt(strings.TrimSpace(string(buf)), 10, 64) | |
if err != nil { | |
panic(err) | |
} | |
return int(n) | |
} | |
EOF | |
$ go build udpbufcap.go | |
$ ./udpbufcap base | |
keep rcvbuf as is | |
i= 0 buf[:16]="seq=00000000!\x00\x00\x00" | |
i= 1 buf[:16]="seq=00000001!\x00\x00\x00" | |
i= 2 buf[:16]="seq=00000002!\x00\x00\x00" | |
(...) | |
i= 90 buf[:16]="seq=00000090!\x00\x00\x00" | |
i= 91 buf[:16]="seq=00000091!\x00\x00\x00" | |
i= 92 buf[:16]="seq=00000092!\x00\x00\x00" | |
$ ./udpbufcap test | |
set rcvbuf to 8738000 | |
i= 0 buf[:16]="seq=00000000!\x00\x00\x00" | |
i= 1 buf[:16]="seq=00000001!\x00\x00\x00" | |
i= 2 buf[:16]="seq=00000002!\x00\x00\x00" | |
(...) | |
i= 7583 buf[:16]="seq=00007583!\x00\x00\x00" | |
i= 7584 buf[:16]="seq=00007584!\x00\x00\x00" | |
i= 7585 buf[:16]="seq=00007585!\x00\x00\x00" | |
$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment