简体   繁体   中英

How do I find a computer's IP address?

I am writing a program in C++ which uses network sockets. I need to find out what the computer's IP address is, so I can display it to the user. The program must run on Windows and Linux.

I have heard somewhere that a computer can have multiple IP addresses. I want the one that other programs on different computers can use to connect to the computer.

Here is the relevant code I already have (the variables are declared in other places):

master = new fd_set;
FD_ZERO(master);
struct sockaddr_in my_addr;

listener = socket(PF_INET, SOCK_STREAM, 0);

my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = INADDR_ANY;
memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero);

bind(listener, (struct sockaddr *)&my_addr, sizeof my_addr);

listen(listener, 10);

FD_SET(listener, master);

fdmax = listener;

I have heard somewhere that a computer can have multiple IP addresses. I want the one that other programs on different computers can use to connect to the computer.

Well... that could be any of them. If a computer has multiple IP addresses it can be accessed on any one of them. Of course one of them could be subject to different firewall rules or they could be on two completely different segments but there's no way to detect any and all of these circumstances.

I posted a similar question, but on OS X recently. The answer that I received was to use either 0.0.0.0 or INADDR_ANY. This will cause your socket to listen on all available addresses, so you don't need to figure out which one is the "right" one.

On Windows, you want to use GetAdaptersAddresses - this lists all of the adapters in your machine and the IP addresses bound to them. It supports IPv6 addresses too. You can also use gethostbyname , but that doesn't support IPv6.

On Linux, we read /proc/net/dev and /proc/net/if_inet6 and parse the results of that.

我相信您可以将getaddrinfo()与侦听器套接字一起使用,以获取绑定到的套接字的IP地址。

It depends if you're trying to get your LAN IP address (ie the address of your computer within the set of your computers) or the IP address your service provider gives to you every time you connect to the internet. The latter can be identified with a query (I guess that you would find a proper C++ library that does that with little Googling) to some IP detecting web services.

If you want a quick and dirty solution you could try to wget http://www.whatismyip.org and read back the contents.

您可以在C ++项目中使用轻量级的客户机/服务器套接字类作为参考。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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