Home >Backend Development >C++ >How to Programmatically Get a Linux Server's Public IP Address in C ?

How to Programmatically Get a Linux Server's Public IP Address in C ?

DDD
DDDOriginal
2024-12-24 05:24:13674browse

How to Programmatically Get a Linux Server's Public IP Address in C  ?

Determining the IP Address of a Linux Machine in C

Problem

How do we programmatically obtain the IP addresses of a Linux server running our application, particularly the external (public) one?

Linux Network Interfaces

A Linux server typically has multiple network interfaces, each with its own IP address. It has:

  • Loopback interface: 127.0.0.1
  • Internal management interface: 172.16.x.x
  • External public interface: 80.190.x.x

Solution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn