你如何从一个打开的TCPConn*中获取IP地址?

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

How can you retrieve the IP address from an open TCPConn*?

问题

我有一个从TCPListener.acceptTCP接受的TCPConn*。我想要只获取IP地址(不包含端口信息),作为一个字符串或IP。有什么正确的(即最小的类型转换/字符串操作)方法可以实现这一点?

英文:

I have a TCPConn* that I've accepted from a TCPListener.acceptTCP. I'd like to get only the IP address (no port information) as a string or IP. What is the correct (i.e. minimal casting/string manipulation) way to accomplish that?

答案1

得分: 8

获取IP地址,作为IP对象,最直接的方法应该是

tcpconn.RemoteAddr().(*net.TCPAddr).IP

使用类型断言没有问题,在这种情况下实际上是可以预期的。

英文:

To get the IP, as an IP object, the most straightforward way should be

tcpconn.RemoteAddr().(*net.TCPAddr).IP

There is nothing wrong with using type assertions, and in cases like this it's actually expected.

huangapple
  • 本文由 发表于 2012年11月12日 12:52:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/13338537.html
匿名

发表评论

匿名网友

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

确定