英文:
How to find IP:Port of incoming client in TCP Connection
问题
在接收到conn, err := listener.Accept()的连接后,我想要找到连接的另一端客户端的地址。我尝试使用conn.LocalAddr()和conn.RemoteAddr()来实现这个目的(文档)。.LocalAddr()只会返回服务器进程的地址,而.RemoteAddr()会返回客户端的IP地址,但端口号与我所知道的客户端绑定的端口号非常不同。
如果有任何区别的话,我正在使用在同一台机器上运行的两个独立进程。一个是客户端,一个是服务器。有没有其他方法可以找到客户端的正确IP:端口?我应该使用LocalAddr还是RemoteAddr?
英文:
After receiving a connection from conn, err := listener.Accept(), I want to find the address of the client at the other end of the conn. I've tried doing this with conn.LocalAddr() and conn.RemoteAddr() (Documentation). .LocalAddr() just gives the address of the server's process. .RemoteAddr() gives the right IP for the client but a very different port number from what I know the client to be binded to.
If it makes any difference, Im doing this with two separate processes running on the same machine. One is a client, one is a server. Any ideas as to how else I can find the correct IP:Port of the client? Am I to use either LocalAddr or RemoteAddr?
答案1
得分: 7
在OSX上,使用go 1.4版本时,通过conn.RemoteAddr()报告的主机/端口组合与netstat输出相比是正确的。
package main
import (
"fmt"
"net"
"time"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err)
}
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
fmt.Println(conn.RemoteAddr())
time.Sleep(time.Minute)
conn.Close()
}
}
运行结果如下:
$ go run foo.go
127.0.0.1:63418
$ netstat -an | grep 8080
tcp4 0 0 127.0.0.1.8080 127.0.0.1.63418 ESTABLISHED
tcp4 0 0 127.0.0.1.63418 127.0.0.1.8080 ESTABLISHED
英文:
On OSX, using go 1.4 the host / port combo reported by conn.RemoteAddr() is correct when compared against netstat output.
package main
import (
"fmt"
"net"
"time"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err)
}
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
fmt.Println(conn.RemoteAddr())
time.Sleep(time.Minute)
conn.Close()
}
}
$ go run foo.go
127.0.0.1:63418
$ netstat -an | grep 8080
tcp4 0 0 127.0.0.1.8080 127.0.0.1.63418 ESTABLISHED
tcp4 0 0 127.0.0.1.63418 127.0.0.1.8080 ESTABLISHED
答案2
得分: -4
netstat -a 1 -f 是在Windows命令行中的命令。我是一个命令行的人,这个命令可以工作,通过重定向将结果写入文件。这个命令每秒重新运行一次,-f 参数用于解析DNS名称。
英文:
netstat -a 1 -f in the windows shell. I'm a command line guy, this works, write it to a file via redirect. This will rerun every second, the f is to resolve DNS name.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论