Örnek :
Kod: Tümünü seç
#include <arpa/inet.h> // for inet_ntop()
#include <ifaddrs.h> // for getifaddrs()
#include <stdio.h>
#include <string.h>
int main() {
struct ifaddrs *ifap, *ifa;
struct sockaddr_in *sa;
char *addr;
// get the linked list of network interface addresses
if (getifaddrs(&ifap) == -1) {
perror("getifaddrs");
return 1;
}
// iterate through the list and print the IP address of each interface
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr->sa_family==AF_INET) {
sa = (struct sockaddr_in *) ifa->ifa_addr;
addr = inet_ntoa(sa->sin_addr);
printf("Interface: %s\nIP address: %s\n", ifa->ifa_name, addr);
}
}
// free the list when we're done with it
freeifaddrs(ifap);
return 0;
}

Kod: Tümünü seç
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
struct ifaddrs *ifap;
struct ifaddrs *ifa;
struct sockaddr_in *sa;
char *addr;
getifaddrs(&ifap);
for (ifa = ifap; ifa; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr->sa_family == AF_INET)
{
sa = (struct sockaddr_in *) ifa->ifa_addr;
addr = inet_ntoa(sa->sin_addr);
printf("Interface: %s\tAddress: %s\n", ifa->ifa_name, addr);
}
}
freeifaddrs(ifap);
return 0;
}

Açıklama :
C kullanarak , bir aygıtın IP adresini bulmak için <ifaddrs.h> başlık dosyasından getifaddrs işlevini kullanabilirsiniz. Bu işlev, aygıtın IP adresi ve diğer ağ bilgileri hakkında bilgi içeren ağ arabirimi adres yapılarının bağlantılı bir listesini alır.
Cihazın IP adresini bulmak için getifaddrs işlevini nasıl kullanabileceğinize bir örnek :
Kod: Tümünü seç
#include <stdio.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
int main() {
struct ifaddrs *addrs, *tmp;
int status = getifaddrs(&addrs);
if (status == -1) {
perror("getifaddrs");
return 1;
}
// Iterate over the linked list of network interface address structures
for (tmp = addrs; tmp != NULL; tmp = tmp->ifa_next) {
// Check if the current structure is for an IPv4 address
if (tmp->ifa_addr->sa_family == AF_INET) {
// Convert the IP address to a string and print it
char ip_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(((struct sockaddr_in*)tmp->ifa_addr)->sin_addr),
ip_str, INET_ADDRSTRLEN);
printf("%s: %s\n", tmp->ifa_name, ip_str);
}
}
// Free the memory allocated by getifaddrs
freeifaddrs(addrs);
return 0;
}

Bu kod, getifaddrs kullanarak ağ arabirimi adres yapılarının bağlantılı bir listesini alır, ardından listeyi yineler ve IPv4 adresine sahip her arabirimin IP adresini yazdırır. inet_ntop işlevi kullanılır.