Skip to content

Commit

Permalink
Merge pull request #40 from libp2p/fix/24
Browse files Browse the repository at this point in the history
check for reuseport support by opening a socket, not listening.
  • Loading branch information
Stebalien authored Jan 29, 2018
2 parents f10be97 + 68e8434 commit 5b959e4
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
13 changes: 7 additions & 6 deletions available_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"sync"
"syscall"
"time"

sockaddrnet "github.com/libp2p/go-sockaddr/net"
)

var (
Expand All @@ -15,7 +17,7 @@ var (
)

// Available returns whether or not SO_REUSEPORT is available in the OS.
// It does so by attepting to open a tcp listener, setting the option, and
// It does so by attepting to open a tcp socket, setting the option, and
// checking ENOPROTOOPT on error. After checking, the decision is cached
// for the rest of the process run.
func available() bool {
Expand All @@ -24,14 +26,13 @@ func available() bool {
}

func checkReusePort() {
// there may be fluke reasons to fail to add a listener.
// there may be fluke reasons to fail to open a socket.
// so we give it 5 shots. if not, give up and call it not avail.
for i := 0; i < 5; i++ {
// try to listen at tcp port 0.
l, err := listenStream("tcp", "127.0.0.1:0")
// try to setup a TCP socket.
fd, err := socket(sockaddrnet.AF_INET, sockaddrnet.SOCK_STREAM, sockaddrnet.IPPROTO_TCP)
if err == nil {
l.Close() // Go back to the Shadow!
// no error? available.
unix.Close(fd)
hasReusePort = true
return
}
Expand Down
2 changes: 1 addition & 1 deletion reuse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func TestDialSelf(t *testing.T) {
t.Fatal(err)
}
_, err = Dial("tcp4", l.Addr().String(), l.Addr().String())
if err != ErrDialSelf {
if err == nil {
t.Fatal("should have gotten an error for dialing self")
}
}
Expand Down

0 comments on commit 5b959e4

Please sign in to comment.