Home >Backend Development >C++ >How to Programmatically Get a Linux Server's Public IP Address in C ?
How do we programmatically obtain the IP addresses of a Linux server running our application, particularly the external (public) one?
A Linux server typically has multiple network interfaces, each with its own IP address. It has:
The getifaddrs function can be used to retrieve all the IP addresses associated with a machine. It provides a linked list of ifaddrs structures. Here's a C example:
#include <stdio.h> #include <sys/types.h> #include <ifaddrs.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> using namespace std; int main() { struct ifaddrs *ifAddrStruct, *ifa; void *tmpAddrPtr; getifaddrs(&ifAddrStruct); for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) { continue; } if (ifa->ifa_addr->sa_family == AF_INET) { 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) { 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; }
This code iterates through all the network interfaces and prints the IP addresses for both IPv4 and IPv6 addresses.
By inspecting the network interface names (e.g., eth0, eth1, etc.), you can identify the external (public) IP address and use it to bind your application.
The above is the detailed content of How to Programmatically Get a Linux Server's Public IP Address in C ?. For more information, please follow other related articles on the PHP Chinese website!