How do I find a computer's IP address?

≯℡__Kan透↙ 提交于 2020-01-14 03:50:10

问题


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;

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


I believe you can use getaddrinfo() with your listener socket, to obtain the IP Address of the socket you bound to.




回答5:


It depends if you're trying to get your LAN IP address (i.e. 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.




回答6:


You can use the light-weighted client/server socket class in C++ project for reference.



来源:https://stackoverflow.com/questions/485769/how-do-i-find-a-computers-ip-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!