dongshen9686 2018-12-20 12:17
浏览 449
已采纳

关于套接字的SO_REUSEADDR在golang中不能正常工作吗?

single IP can only support 65535 port to single destination. I hope the client can reuse the old tcp_session immediately during the performance test, even if session is still in time_wait status.

On my Linux machine, I had opened these switch

sysctl -w net.ipv4.tcp_timestamps=1
sysctl -w net.ipv4.tcp_tw_recycle=1
sysctl -w net.ipv4.tcp_tw_reuse=1

Then I write the following code to verify the socket_reuse option with golang. In the code, I bind the local port 12345.

after run first

$go run 1.go

$netstat -nat | grep 12345
tcp        0      0 192.168.1.11:12345         111.161.3.173:80            TIME_WAIT

after run secondary

$go run 1.go
Client Connect() called error: cannot assign requested address

It seems that the SO_REUSEADDR can not work. Can Anyone help to resolve this ?

package main

import (
    "fmt"
    . "syscall"
)

func main() {
    var (
        clientsock int
        serveraddr SockaddrInet4
        err        error
    )

    if clientsock, err = Socket(AF_INET, SOCK_STREAM, IPPROTO_IP); err != nil {
        fmt.Println("Client Socket() called error:", err.Error())
        return
    }
    SetsockoptInt(clientsock, SOL_SOCKET, SO_REUSEADDR, 1)

    defer Shutdown(clientsock, SHUT_RDWR)

    serveraddr.Addr = [4]byte{111, 161, 3, 173}
    serveraddr.Port = 80

    err = Bind(clientsock, &SockaddrInet4{
        Port: 12345,
    })

    if err = Connect(clientsock, &serveraddr); err != nil {
        fmt.Println("Client Connect() called error:", err.Error())
        return
   }
}
  • 写回答

1条回答 默认 最新

  • douchuo9476 2018-12-20 14:45
    关注

    You ought to add two changes to your code:

    1) Set socket option unix.SO_REUSEPORT.

    if errReusePort := SetsockoptInt(clientsock, SOL_SOCKET, unix.SO_REUSEPORT, 1); errReusePort != nil {
        fmt.Printf("reuse port error: %v
    ", errReusePort)
        return
    }
    

    2) Make your code to connect to distinct remote TCP endpoints. Otherwise, due to single source addr/port, TCP wouldn't be able to distinguish between two identical connections (protocol, src-addr, src-port, dst-addr, dst-port). The example below specifies two remote server addresses in the command-line.

    $ go run main.go 127.0.0.1
    connected
    
    $ go run main.go 127.0.0.2
    connected
    

    Find full working code on playground: https://play.golang.org/p/HYLkWlVH6T4

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 代写uni代码,app唤醒
  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下: