2018-12-20 12:17
浏览 419


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            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 (
    . "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())
    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())
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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)

    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
    $ go run main.go

    Find full working code on playground:

    解决 无用
    打赏 举报

相关推荐 更多相似问题