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

关于套接字的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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测