简体   繁体   English

如何从远程机器获取 ip 地址?

[英]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:可能的例外情况及其无关紧要的原因:

  • You get the address of a NAT device - well, in that case your PC doesn't have an Internet address, what were you planning to do with the 10.xyz address you probably do have?您获得了 NAT 设备的地址 - 好吧,在这种情况下,您的 PC 没有 Internet 地址,您打算如何处理您可能拥有的 10.xyz 地址?
  • You don't get an address at all, as you're not connected to the Internet - if you can't connect, it's unlikely another computer could do anythin useful with your IP address.您根本没有地址,因为您没有连接到互联网 - 如果您无法连接,另一台计算机不太可能对您的 IP 地址做任何有用的事情。
  • You do get back an IP, but nobody can connect to it - you're likely behind a filtering firewall that refuses any incoming connection.您确实得到了 IP,但没有人可以连接到它 - 您可能位于拒绝任何传入连接的过滤防火墙后面。 It's quite unlikely that the firewall would accept traffic on another IP address that connects to the same computer.防火墙不太可能接受连接到同一台计算机的另一个 IP 地址上的流量。 Even if that is the case, it might be impossible to discover.即使是这样,也可能无法发现。 And it would be hell for FTP. FTP 将是地狱。

If you know the name of the machine your application run, just use gethostbyname().如果您知道您的应用程序运行的机器的名称,只需使用 gethostbyname()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM