Skip to content

Instantly share code, notes, and snippets.

@nariyu
Created July 16, 2015 09:14
Show Gist options
  • Save nariyu/beaabf90c8fb39eff9d8 to your computer and use it in GitHub Desktop.
Save nariyu/beaabf90c8fb39eff9d8 to your computer and use it in GitHub Desktop.
空いてるポートを探すやーつ
package xxx
import (
"fmt"
"net"
)
// 使える TCP ポートを探すんだ
func searchUsablePort(startPort, endPort int) int {
var usablePort = -1
for i := startPort; i <= endPort; i++ {
tcpAddr, err := net.ResolveTCPAddr("tcp4", fmt.Sprintf("localhost:%d", i))
if err != nil {
usablePort = i
break
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
usablePort = i
break
}
defer conn.Close()
}
return usablePort
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment