英文:
How do I get a network client's IP converted to a string in Golang?
问题
我正在尝试在连接到服务器时获取客户端的IP地址。尝试使用RemoteAddr()
函数返回一个地址类型,虽然我可以使用fmt.Println
将其打印到控制台,但我想将该值赋给一个字符串变量。
这种做法可行吗?还是有更好的方法来获取连接的客户端IP地址?
我正在处理的函数示例(strRemoteAddr
赋值部分是有问题的,但我将其保留为占位符...):
func GrabInput(conn net.Conn, strFromListenerNumber string) {
var strMessage string
var strRemoteAddr string
bufIncoming := make([]byte, 1024)
strRemoteAddr = conn.RemoteAddr()
for {
bytesRead, err := conn.Read(bufIncoming)
if err != nil {
LogEvent(strFromListenerNumber, err.Error())
return
}
strMessage = string(bufIncoming[0 : bytesRead-1])
LogEvent(strFromListenerNumber+": "+strRemoteAddr, strMessage)
}
}
请注意,这只是一个翻译结果,我无法运行或测试代码。
英文:
I'm trying to get a client IP when a connection is made to a server. Trying to use RemoteAddr()
returns an addr-type, and while I can print to the console using fmt.Println
, I'm trying to assign the value to a string variable.
Is this possible? Or is there a better way to pull a connected client's IP address?
Sample of the function I'm working on (the strRemoteAddr
assignment is the problem part, but I left it in as a placeholder...):
func GrabInput(conn net.Conn, strFromListenerNumber string) {
var strMessage string
var strRemoteAddr string
bufIncoming := make([]byte, 1024)
strRemoteAddr = conn.RemoteAddr()
for {
bytesRead, err := conn.Read(bufIncoming)
if err != nil {
LogEvent(strFromListenerNumber, err.Error())
return
}
strMessage = string(bufIncoming[0 : bytesRead-1])
LogEvent(strFromListenerNumber+": "+strRemoteAddr, strMessage)
}
}
答案1
得分: 20
将其转换为*net.TCPAddr
类型
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
fmt.Println(addr.IP.String())
}
英文:
Convert it to *net.TCPAddr
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
fmt.Println(addr.IP.String())
}
答案2
得分: 17
似乎只需要使用strRemoteAddr = conn.RemoteAddr().String()
,net.Addr
类型有一个String()
方法用于返回字符串表示形式。
英文:
Seems just
strRemoteAddr = conn.RemoteAddr().String()
can do, net.Addr type has method String() for string representation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论