Problem:
Determine the IP addresses of a Linux machine programmatically using C , specifically targeting the public IP address among multiple potential addresses.
Solution:
The getifaddrs() function provides a more reliable method for retrieving IP addresses on Linux and POSIX-compliant operating systems. It returns a linked list of ifaddrs structures, each representing a network interface and its associated addresses. Here's a code example demonstrating its usage:
#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) { continue; } 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 IP Address %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 IP Address %s\n", ifa->ifa_name, addressBuffer); } } if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct); return 0; }
In the code, getifaddrs() fills the ifAddrStruct linked list with network interface information. Each ifaddrs structure contains an ifa_addr member, which is a pointer to the socket address structure representing the IP address. AF_INET is for IPv4 addresses, and AF_INET6 is for IPv6 addresses.
The code iterates through the linked list, checks if the ifa_addr is valid, and then retrieves and prints the IP address string by converting it to a human-readable format using inet_ntop().
To identify the public IP address, you can check the network interface name (e.g., "eth0") or compare the IP addresses to determine which one matches the external network.
The above is the detailed content of How to Programmatically Retrieve a Linux Machine's IP Addresses in C ?. For more information, please follow other related articles on the PHP Chinese website!