douwei1128 2018-06-10 05:47
浏览 330
已采纳

Go的net.Listener Addr()有什么用途?

Go's net.Listener interface looks like this:

type Listener interface {
    // Accept waits for and returns the next connection to the listener.
    Accept() (Conn, error)

    // Close closes the listener.
    // Any blocked Accept operations will be unblocked and return errors.
    Close() error

    // Addr returns the listener's network address.
    Addr() Addr
}

But what is the Addr actually used for? If I had to implement my own Listener that just returned an empty Addr().String() but accepted and closed connections just fine, what implications would that have?

  • 写回答

2条回答 默认 最新

  • donglianglu8136 2018-06-10 05:55
    关注

    Some network protocols allow you to create a listener which listens on a random address. This is commonly used when you want to run multiple instances of your service at the same time, and thus you can't have them all listening on the same address. In these cases, the kernel will find one that's available, and put your listener there. But once you have a random address, you need to know what that address is so you can advertise it.

    For example, with TCP & UDP, you can specify 0 as your port number:

    package main
    
    import (
        "fmt"
        "net"
    )
    
    func main() {
        l, _ := net.Listen("tcp4", ":0")
        fmt.Printf("Addr: %s
    ", l.Addr())
    }
    

    Results in something like:

    Addr: 0.0.0.0:37733
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作