[英]How do you get the ip address from a remote machine?
I'm writing c++ code that I need to run on both windows and linux and I'm looking for a function call that will return the ip address of the box the app is running on. I'm writing c++ code that I need to run on both windows and linux and I'm looking for a function call that will return the ip address of the box the app is running on. Is there such one?
有这样的吗?
IF you can use boost, take a look at如果您可以使用boost,请查看
How to get IP addresss of boost::asio::ip::tcp::socket? 如何获取 boost::asio::ip::tcp::socket 的 IP 地址?
Call socket(), then getsockname().调用socket(),然后调用getsockname()。
You can do it but it's generally a bad idea.你可以这样做,但这通常是一个坏主意。
ioctl SIOCGIFCONF as described in "man netdevice" explains this. “man netdevice”中描述的 ioctl SIOCGIFCONF 解释了这一点。
The reason it's a bad idea is that you probably won't get what you want out of it.这是一个坏主意的原因是你可能不会得到你想要的东西。
The machine could have several or many IP addresses, you won't know which one(s) are public.该机器可能有多个或多个 IP 地址,您不会知道哪些是公开的。 It could be behind a NAT gateway (or several) in which case none of them may be public.
它可能位于 NAT 网关(或多个)后面,在这种情况下,它们都可能不是公共的。
You just can't use that info particularly usefully.您只是不能特别有用地使用该信息。 Whatever you want it for, it's probably not a good idea to do it.
无论您想要什么,都可能不是一个好主意。
Best idea is to use a webservice.最好的主意是使用网络服务。 Connect to a known server, have it send back the IP that you used to contact it.
连接到已知服务器,让它发回您用来联系它的 IP。 That will tell you the IP address (OK, an IP address) that your PC uses when talking to the outside world.
这将告诉您 PC 在与外界通信时使用的IP 地址(好的,IP 地址)。
Possible exceptions and why they do not matter:可能的例外情况及其无关紧要的原因:
If you know the name of the machine your application run, just use gethostbyname().如果您知道您的应用程序运行的机器的名称,只需使用 gethostbyname()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.