golang get udp socket buffer size

huangapple go评论94阅读模式
英文:

golang get udp socket buffer size

问题

我正在编写一个UDP客户端,并通过SetWriteBuffer设置UDP套接字的发送缓冲区。

addr, _ := net.ResolveUDPAddr("udp", ":8089")
conn, err := net.DialUDP("udp", nil, addr)
err = conn.SetWriteBuffer(64*1024*1024)

以上是代码示例,我想知道如何测试设置的值是否有效,或者在调用SetWriteBuffer函数后如何获取发送缓冲区的值。谢谢大家。

英文:

I'm writing a udp client and set udp socket send buffer by SetWriteBuffer.

   addr, _ := net.ResolveUDPAddr("udp", ":8089")
   conn, err :=net.DialUDP("udp", nil, addr)  
   err =conn.SetWriteBuffer(64*1024*1024)

as above, how can I test set the value is effective or get the send buffer value after call SetWriteBuffer function.
Thank you all.

答案1

得分: 5

在查看net包的代码后,看起来SetWriteBuffer函数会调用setsockopt进行系统调用(对于posix系统)。而GetWriteBuffer没有类似的函数。我能想到的唯一方法是通过另一个系统调用来使用getsockopt函数,代码如下:

addr, _ := net.ResolveUDPAddr("udp", ":8089")
conn, _ := net.DialUDP("udp", nil, addr)
conn.SetWriteBuffer(10 * 1024)
fd, _ := conn.File()
value, _ := syscall.GetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_SNDBUF)
log.Println(value)
fd.Close()
conn.Close()
英文:

After looking at the net package code, it looks like SetWriteBuffer makes a syscall to setsockopt (for posix). There is no similar function for GetWriteBuffer. The only way i can think to do this is by making another syscall to getsockopt like so.

addr, _ := net.ResolveUDPAddr("udp", ":8089")
conn, _ := net.DialUDP("udp", nil, addr)
conn.SetWriteBuffer(10 * 1024)
fd, _ := conn.File()
value, _ := syscall.GetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_SNDBUF)
log.Println(value)
fd.Close()
conn.Close()

答案2

得分: 1

检查SetWriteBuffer返回的错误值。例如,

package main

import (
	"log"
	"net"
)

func main() {
	addr, err := net.ResolveUDPAddr("udp", ":8089")
	conn, err := net.DialUDP("udp", nil, addr)

	err = conn.SetWriteBuffer(64 * 1024 * 1024)
	if err != nil {
		log.Print(err)
	}
}

请注意,这段代码是用于设置UDP连接的写缓冲区大小。如果SetWriteBuffer返回错误,将会打印错误信息。

英文:

Check the error value returned by SetWriteBuffer. For example,

package main

import (
	"log"
	"net"
)

func main() {
	addr, err := net.ResolveUDPAddr("udp", ":8089")
	conn, err := net.DialUDP("udp", nil, addr)

	err = conn.SetWriteBuffer(64 * 1024 * 1024)
	if err != nil {
		log.Print(err)
	}
}

huangapple
  • 本文由 发表于 2017年4月17日 19:22:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/43450463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定