How do I get a network client's IP converted to a string in Golang?

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

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.

huangapple
  • 本文由 发表于 2015年4月17日 06:30:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/29687102.html
匿名

发表评论

匿名网友

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

确定