I needed to find the IP address for the local machine on of the webservices. In C#, I have
ManagementObjectSearcher objC = new ManagementObjectSearcher("SELECT * FROM W开发者_如何学运维in32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection objCollection = objC.Get();
How could I do it in C++ Linux?
getifaddrs() will return a list of structures of all the interfaces in the machine. There is an example at the bottom of the man page.
You can also use ioctl with the SIOCGIFCONF parameter. There is an example here
My favorite way:
- Make a UDP socket
- Bind to wildcard
- Connect to
1.2.3.41.1.1.1 - getsockname
1.2.3.4 is an impossible IP address that happens to be treated by all hosts as outobund. 1.1.1.1 is CloudFlare's DNS server with multicast routing so your host can't be it. (If they ever make 1. allocatable you will have to use 0.2.3.4 which can potentially invoke undefined behavior).
You will need to update this for IPv6 of course.
Your specific question is answered in the following pages:
- linux-c-get-the-ip-address-of-local-computer
- get-the-ip-address-of-local-computer
But here is more information about BSD sockets. Beej's Guide to Network Programming is a good place to learn more.
C++ in linux using the system call 'getifaddr' to get all interface of your network card. Here are two function and a struct you need.
struct ifaddrs{
struct ifaddrs *ifa_next; /* Pointer to the next structure. */
char *ifa_name; /* Name of this network interface. */
struct sockaddr *ifa_addr; /* Network address of this interface. */
...
}
int getifaddrs(struct ifaddrs **ifap); //to get all interface config fed to ifap
void freeifaddrs(struct ifaddrs *ifa); //to free ifa
And here is an example provided by user Twelve47 at Get the IP address of the machine to get IPv4 and IPv6 address of all interfaces:
#include <stdio.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
int main (int argc, const char * argv[]) {
struct ifaddrs * ifAddrStruct=NULL;
struct ifaddrs * ifa=NULL;
void * tmpAddrPtr=NULL;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa ->ifa_addr->sa_family==AF_INET) { // check it is IP4
// is a valid IP4 Address
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
printf("'%s': %s\n", ifa->ifa_name, addressBuffer);
} else if (ifa->ifa_addr->sa_family==AF_INET6) { // check it is IP6
// is a valid IP6 Address
tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
char addressBuffer[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
printf("'%s': %s\n", ifa->ifa_name, addressBuffer);
}
}
if (ifAddrStruct!=NULL)
freeifaddrs(ifAddrStruct);//remember to free ifAddrStruct
return 0;
}
精彩评论