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#include #include 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3