LoginSignup
16
11

More than 5 years have passed since last update.

TCPの空きポートをListenする

Posted at

はじめに

サーバを起動する時にポートは何でもよいので空きポートをListenしたい事がありました。
ウェルノウンポート以外を順に調べるしかないのかと思っていたのですが、
そんな面倒はなくポート0をListenすると空きポートが割り当てられます。

サンプル

以下はGoで書いた検証コードです。

main.go
package main

import (
    "fmt"
    "net"
)

func main() {
    l, err := net.Listen("tcp", "localhost:0")
    if err == nil {
        defer l.Close()

        addr := l.Addr().String()
        _, port, err := net.SplitHostPort(addr)

        if err == nil {
            fmt.Printf("    listen port: %s\n", port)
        } else {
            fmt.Printf("    %s\n", addr)
        }
    } else {
        fmt.Println("can't listen")
    }
}

実行する度に異なるポートが割り当てられています。

実行結果
% go run main.go
    listen port: 64522
% go run main.go
    listen port: 64830
% go run main.go
    listen port: 64835
% go run main.go
    listen port: 64838

参考リンク

16
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
11