问题
I know this question has been asked a million times in one form or another, but no question gave me a POSIX-compliant way of doing it.
I need to get the local network address of my computer without using getifaddrs
or any other non POSIX-compliant way of accessing interfaces. Is that possible ?
回答1:
There is no direct support for such a thing but you can use udp sockets (SOCK_DGRAM
) to connect
to a known distant address. Since udp sockets are stateless this doesn't do any network traffic.
Then you can query for the local endpoint of that socket (getsockname
) to obtain the local IP adress through which your system would route. Again since udp is stateless this just queries your local routing tables and no real network traffic is issued.
Don't forget to close the socket after that.
Remote public nameservers are good for that purpose. You can test for several of them
- one of them might occasionally be down or there might be no route for some reason to that part of the world
- your process may be on the same local network as the server and you might only obtain some special local address
- test for IPv4 and IPv6 addresses
回答2:
No, that is not possible, as posix does not specify any API to access that information.
Unixes typically support getifaddrs, or the SIOCGIFCONF ioctl , so use one of them or some other system demendant API. Note that there can be (and usually are) several network interfaces on a machine, and you have to figure out which you're interested in.
回答3:
POSIX has no concept of "network", even less IP. So no.
Besides, a machine can have lots of network addresses (at least loopback, one or several for each network card, at least three IPv6 addresses, ...), "the network address" isn't well defined anyway.
回答4:
Quite simple, surely:
#include <unistd.h>
int main(int argc, char* argv[]) {
return 8 == write(1, "0.0.0.0\n", 8) ? 0 : 1;
}
回答5:
#include <stdio.h>
int main(int argc, char* argv[]) {
printf("127.0.0.1\n");
}
来源:https://stackoverflow.com/questions/8645566/is-there-a-posix-compliant-way-of-getting-local-network-ip-address-of-my-compute