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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?