Help us understand the problem. What is going on with this article?

TCPの空きポートをListenする

More than 5 years have passed since last update.

はじめに

サーバを起動する時にポートは何でもよいので空きポートを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

参考リンク

kadinche
弊社では 2008年の会社設立当初から、一貫して VR ソリューションの研究開発に取り組んでいます。
https://www.kadinche.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした