How to Programmatically Obtain the IP Addresses of a Linux Machine in C
Introduction:
This article addresses a common programming challenge: determining the IP addresses of a Linux machine running an application written in C . The focus here is on obtaining the external or public IP address of the server.
Problem Statement:
The task is to develop a C program that retrieves the IP addresses of a Linux machine, specifically the one assigned to a specified network (the public IP). This ensures the application can bind itself to the desired external address for network communication.
Solution:
To solve this problem, we leverage the getifaddrs() function call, which is part of the POSIX standard and thus available on Linux. This function provides a convenient way to iterate through all network interfaces and retrieve their IP addresses.
Implementation:
The following C code demonstrates how to use the getifaddrs() function:
#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; }
Explanation:
This code iterates through all network interfaces using the ifa loop and checks the address family of each interface. If it's IPv4 or IPv6, it converts the address to a string and prints it along with the interface name.
This approach enables you to detect all IP addresses assigned to the Linux machine and identify the desired public IP for binding purposes.
The above is the detailed content of How to Programmatically Get a Linux Machine's Public IP Address in C ?. For more information, please follow other related articles on the PHP Chinese website!