Skip to content

Commit

Permalink
Add ability to detect free port
Browse files Browse the repository at this point in the history
Signed-off-by: Syrone Wong <[email protected]>
  • Loading branch information
wongsyrone committed Jan 10, 2020
1 parent ed9a135 commit c379ab8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
BUILDDIR=$(shell pwd)/build
SOURCES=github.com/trojan-gfw/igniter-go-libs/clash github.com/trojan-gfw/igniter-go-libs/tun2socks
SOURCES= \
github.com/trojan-gfw/igniter-go-libs/clash \
github.com/trojan-gfw/igniter-go-libs/tun2socks \
github.com/trojan-gfw/igniter-go-libs/freeport

all: ios android

Expand Down
40 changes: 40 additions & 0 deletions freeport/freeport.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Taken from https://github.com/phayes/freeport
package freeport

import (
"net"
)

// GetFreePort asks the kernel for a free open port that is ready to use.
func GetFreePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}

l, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}

// GetFreePort asks the kernel for free open ports that are ready to use.
func GetFreePorts(count int) ([]int, error) {
var ports []int
for i := 0; i < count; i++ {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return nil, err
}

l, err := net.ListenTCP("tcp", addr)
if err != nil {
return nil, err
}
defer l.Close()
ports = append(ports, l.Addr().(*net.TCPAddr).Port)
}
return ports, nil
}

0 comments on commit c379ab8

Please sign in to comment.