Identifying the IP addresses of a Linux server is essential for network communication and application deployment. This article presents a programmatic solution in C to effectively retrieve the IP addresses of a Linux machine.
The objective is to programmatically obtain the IP addresses of a Linux server within a C application. The server may have multiple IP addresses, including a localhost address, an internal (management) address, and an external (public) address. The goal is to retrieve the external IP address for application binding.
The standard C library provides the getifaddrs() function to obtain information about the network interfaces and IP addresses of a system. Here's an example that uses getifaddrs() to print all IPv4 and IPv6 addresses of the local machine:
#include <stdio.h> #include <sys/types.h> #include <ifaddrs.h> int main() { 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) { // IPv4 address tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); printf("IPv4 Address %s\n", addressBuffer); } else if (ifa->ifa_addr->sa_family == AF_INET6) { // IPv6 address tmpAddrPtr = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr; char addressBuffer[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); printf("IPv6 Address %s\n", addressBuffer); } } if (ifAddrStruct != NULL) { freeifaddrs(ifAddrStruct); } return 0; }
To retrieve the external IP address, you can use a similar approach but specifically looking for the interface that connects to the external network. You can use siocgifaddr with SIOCGIFADDR to retrieve the IP address of a specific interface.
The getifaddrs() function and siocgifaddr with SIOCGIFADDR provide robust methods for retrieving the IP addresses of a Linux machine in C . These approaches enable applications to dynamically adapt to network changes and establish necessary network connections.
The above is the detailed content of How Can I Programmatically Determine a Linux Server's IP Addresses in C ?. For more information, please follow other related articles on the PHP Chinese website!