[英]Get syscall.Handle from a Go *net.UDPConn on Windows?
如何在Windows上获取*net.UDPConn
的底层syscall.Handle
? 我希望这个句柄通过syscall.SetsockoptInt
设置IP_MULTICAST_TTL
。 在Linux上我执行以下操作:
func setTTL(conn *net.UDPConn, ttl int) error {
f, err := conn.File()
if err != nil {
return err
}
defer f.Close()
fd := int(f.Fd())
return syscall.SetsockoptInt(fd, syscall.SOL_IP, syscall.IP_MULTICAST_TTL, ttl)
}
但是在Windows上, *net.UDPConn
的File()
的隐式dup
失败了:
04:24:49 main.go:150:dup:不支持windows
并在源代码中标记为待办事项。 我怎么能得到这个句柄? 是否还有其他方法可以设置TTL?
我已将缺点提交给Go问题跟踪器:
简短的回答是不可能的。 但既然这不是你想听到的答案,我会以正确的方式和错误的方式来解决问题。
dup()
。 显然正确的方法有一些问题......但我强烈建议这样做。 Go需要Windows开发人员来解决这些类型的严重问题。 在Windows中无法完成的唯一原因是没有人实现该功能
在您编写的补丁被接受并发布之前,您可以通过不安全的方式伪造它。 以下代码的工作方式是镜像net.UDPConn
的确切结构。 这包括复制构成UDPConn
网络中的所有结构。 然后使用unsafe
断言本地UDPConn
与net的UDPConn
相同。 编译器无法检查这个并接受你的话。 是的内部net
永远改变,它会编译,但上帝知道它会怎么做。
所有代码都未经过测试。
package reallyunsafenet
import (
"net"
"sync"
"syscall"
"unsafe"
)
// copied from go/src/pkg/net/fd_windows.go
type ioResult struct {
qty uint32
err error
}
// copied from go/src/pkg/net/fd_windows.go
type netFD struct {
// locking/lifetime of sysfd
sysmu sync.Mutex
sysref int
closing bool
// immutable until Close
sysfd syscall.Handle
family int
sotype int
isConnected bool
net string
laddr net.Addr
raddr net.Addr
resultc [2]chan ioResult
errnoc [2]chan error
// owned by client
rdeadline int64
rio sync.Mutex
wdeadline int64
wio sync.Mutex
}
// copied from go/src/pkg/net/udpsock_posix.go
type UDPConn struct {
fd *netFD
}
// function to get fd
func GetFD(conn *net.UDPConn) syscall.Handle {
c := (*UDPConn)(unsafe.Pointer(conn))
return c.fd.sysfd
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.