gpt4 book ai didi

windows - 从 Windows 上的 Go *net.UDPConn 获取 syscall.Handle?

转载 作者:IT王子 更新时间:2023-10-29 01:12:31 26 4
gpt4 key购买 nike

如何在 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.UDPConnFile() 中的隐式 dup 失败了:

04:24:49 main.go:150: dup: not supported by windows

并且在源代码中被标记为待办事项。我怎样才能得到这个句柄?如果没有,还有其他方法可以设置 TTL 吗?

更新0

我已将缺点提交给 Go 问题跟踪器:

最佳答案

简短的回答是不可能的。但既然那不是你想听到的答案,我会告诉你解决问题的正确方法和错误方法。

正确的做法:

  1. 为 Windows 实现 dup()
  2. 作为变更集提交给 Go
  3. 等待发布后使用

显然,正确的方法存在一些问题……但我强烈建议您这样做。 Go 需要 Windows 开发人员来解决这些类型的严重问题。这不能在 Windows 中完成的唯一原因是没有人实现该功能

错误的方式:

在你编写的补丁被接受并发布之前,你可以通过 unsafe 来伪造它。以下代码通过镜像 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
}

关于windows - 从 Windows 上的 Go *net.UDPConn 获取 syscall.Handle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11319025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com