当前位置: > > > > 如何在 Windows 上使用 Go 读写套接字 fd?
如何在 Windows 上使用 Go 读写套接字 fd?
来源:stackoverflow
2024-04-28 14:51:21
0浏览
收藏
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《如何在 Windows 上使用 Go 读写套接字 fd?》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容
我一直在尝试syscall.Socket创建fd,调用syscall.Connect和syscall.Write()
但是syscall.Write() return err 参数不正确
解决方案
package main
import (
"errors"
"fmt"
"os"
"syscall"
)
func main() {
fd, _ := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
addr := syscall.SockaddrInet4{
Port: 30001,
Addr: [4]byte{172, 16, 1, 222},
}
connectErr := syscall.Connect(fd, &addr)
defer syscall.Close(fd)
if connectErr != nil {
fmt.Println(connectErr)
return
}
writeLen, err := syscall.Write(fd, []byte("test"))
/* file, err := MakeTunFile(uintptr(fd))
if err != nil {
fmt.Println(err)
return
}
writeLen, err := file.WriteString("test") */
fmt.Println(writeLen) // 0
fmt.Println(err) // The parameter is incorrect.
}
// MakeTunFile returns an os.File object from a TUN file descriptor `fd`.
func MakeTunFile(fd uintptr) (*os.File, error) {
if fd < 0 {
return nil, errors.New("TUN file descriptor error")
}
file := os.NewFile(fd, "")
if file == nil {
return nil, errors.New("open TUN file descriptor error")
}
return file, nil
}
本篇关于《如何在 Windows 上使用 Go 读写套接字 fd?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注米云公众号!
