如何在TCP连接中查找IP:传入客户端的端口 [英] How to find IP:Port of incoming client in TCP Connection
问题描述
从conn, err := listener.Accept()
接收到连接后,我想在conn
的另一端找到客户端的地址.我尝试使用conn.LocalAddr()
和conn.RemoteAddr()
(文档)进行此操作. .LocalAddr()
仅提供服务器进程的地址. .RemoteAddr()
为客户端提供正确的IP,但是端口号与我知道要绑定到的客户端完全不同.
如果有什么不同,我将在同一台计算机上运行两个独立的进程来执行此操作.一个是客户端,一个是服务器.关于我还能如何找到客户端的正确IP:Port的任何想法?我可以使用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
?
推荐答案
在OSX上,使用go 1.4将conn.RemoteAddr()
报告的主机/端口组合与netstat输出进行比较是正确的.
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
这篇关于如何在TCP连接中查找IP:传入客户端的端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!