How to get the LocalAddress in GO?

huangapple go评论73阅读模式
英文:

How to get the LocalAddress in GO?

问题

我正在制作一个类似代理的Go Web服务器。我需要获取客户端的信息以便给出响应。以下是我的代码:

func main(){

    li, err := net.Listen("tcp", ":8000")
    if err != nil{
        log.Fatalln(err.Error())
    }
    defer li.Close()

    for{

        conn, err := li.Accept()
        if err != nil {
            log.Fatalln(err.Error())
        }
        local := conn.LocalAddr()
        remote := conn.RemoteAddr()
        fmt.Println(local.Network())
        fmt.Println(remote.String())

        go handleConn(conn)
    }
}

问题是当我运行时,我收到以下错误信息:

local.Network undefined (type func() net.Addr has no field or method Network)

但是文档中说Addr类型有这些方法:

https://golang.org/pkg/net/#Conn

https://golang.org/pkg/net/#Addr

英文:

I'm making a webserver in go that act like a proxy. I need to get the infos about the client to give its response.
Here is my code:

func main(){

	li, err := net.Listen("tcp", ":8000")
	if err != nil{
		log.Fatalln(err.Error())
	}
	defer li.Close()

	for{

		conn, err := li.Accept()
		if err != nil {
			log.Fatalln(err.Error())
		}
		local := conn.LocalAddr
		remote := conn.RemoteAddr
		fmt.Println(string(local.Network))
		fmt.Println(string(remote.String))

		go handleConn(conn)
    }
}

The problem is when i run i receive this message:

local.Network undefined (type func() net.Addr has no field or method Network)

but the documentation says the Addr type has this methods

https://golang.org/pkg/net/#Conn

https://golang.org/pkg/net/#Addr

答案1

得分: 1

你没有调用函数,在你的local变量中只是存储了函数本身。

试试这样写:

local := conn.LocalAddr()
remote := conn.RemoteAddr()
英文:

You are not calling the function, in your local variable you are storing the function itself.

Try this:

local := conn.LocalAddr()
remote := conn.RemoteAddr()

huangapple
  • 本文由 发表于 2017年1月10日 04:07:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/41556060.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定