duanpo6079 2017-04-15 10:12
浏览 332
已采纳

如何使用http.ListenAndServe中的下一个可用端口

I wrote a simple web server to listen on port 8080. But I don't want to use a hard coded port number. What I want is that my server listen on any available port. And I want to know that on what port number my web server is listening.

My code is given bellow:

package main

import (
    "net/http"
)

func main() {       
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)

}
  • 写回答

1条回答 默认 最新

  • duanhao1004 2017-04-15 11:24
    关注

    You may use port 0 to indicate you're not specifying an exact port but you want a free, available port selected by the system:

    http.ListenAndServe(":0", nil)
    

    The problem with this is that you won't be able to find out what port was assigned. So you need to create the net.Listener yourself (using the net.Listen() function), and manually pass it to http.Serve():

    listener, err := net.Listen("tcp", ":0")
    if err != nil {
        panic(err)
    }
    
    fmt.Println("Using port:", listener.Addr().(*net.TCPAddr).Port)
    
    panic(http.Serve(listener, nil))
    

    Example output:

    Using port: 42039
    

    As you can see, you can access the assigned port from the net.Listener, from its net.Addr address (acquired by its Addr() method). net.Addr does not directly give access to the port, but since we created the net.Listener using tcp network stream, the net.Addr will be of dynamic type *net.TCPAddr (which we can acquire with a type assertion), which is a struct and has a field Port int.

    Note that if you don't need the port in your application (e.g. you just want to display it for yourself), you don't need the type assertion, you can just print listener.Addr() (which will contain the port at the end):

    fmt.Println("Address:", listener.Addr())
    

    Example output:

    Address: [::]:42039
    

    Also don't forget to handle returned errors (http.ListenAndServe() in this case). In my example I simply passed it to panic() because http.LitenAndServe() and http.Serve() block if everything goes well (so they only return if there's an error, which I pass to panic()).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。