Skip to content

Instantly share code, notes, and snippets.

@y109
Forked from libesz/get_ip_from_nic.c
Created May 13, 2016 19:24
Show Gist options
  • Save y109/adf62e6e7eec38b8537c13bd1e15e877 to your computer and use it in GitHub Desktop.
Save y109/adf62e6e7eec38b8537c13bd1e15e877 to your computer and use it in GitHub Desktop.
Sample C code to obtain the IP address attached to a selected network interface under Linux.
/*
* Sample C code to obtain the IP address attached to
* a selected network interface under Linux.
*
* Found here: http://www.geekpage.jp/en/programming/linux-network/get-ipaddr.php
*
* Missing includes added.
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
int fd;
struct ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
/* I want to get an IPv4 IP address */
ifr.ifr_addr.sa_family = AF_INET;
/* I want IP address attached to "eth0" */
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ - 1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
/* display result */
printf("%s\n", inet_ntoa(((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment