gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Write Linux C program that prints current IP.
- User
Write Linux C program that prints current IP.
- Assistant
Write Linux C program that prints current IP.
To obtain the current IP address in a Linux system using C, you can utilize the getifaddrs function, which is defined in <ifaddrs.h>. This function retrieves network interface addresses associated with the host. Below is an example C program that retrieves and prints the current IP address of the system.
Here's how you might implement it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
struct ifaddrs *ifaddr, *ifa;
char ipstr[INET6_ADDRSTRLEN];
// Get the list of network interfaces
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
exit(EXIT_FAILURE);
}
// Loop through the list of interfaces
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
// Check if the interface is up and is an IPv4 or IPv6 address
if (ifa->ifa_addr == NULL) {
continue;
}
if (ifa->ifa_addr->sa_family == AF_INET) { // IPv4
// Convert the address to a string
if (inet_ntop(AF_INET, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr, ipstr, sizeof(ipstr)) != NULL) {
printf("%s: IPv4 Address: %s\n", ifa->ifa_name, ipstr);
}
} else if (ifa->ifa_addr->sa_family == AF_INET6) { // IPv6
// Convert the address to a string
if (inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, ipstr, sizeof(ipstr)) != NULL) {
printf("%s: IPv6 Address: %s\n", ifa->ifa_name, ipstr);
}
}
}
freeifaddrs(ifaddr);
return 0;
}
get_ip.c.gcc:
gcc -o get_ip get_ip.c
./get_ip
getifaddrs retrieves the linked list of network interfaces.inet_ntop.lo for localhost or any other inactive interface).Not yet included in a published release.