Created
January 15, 2015 19:16
-
-
Save johntyree/c1bf0c4ec02deb4e6b4a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <string.h> /* for strncpy */ | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <sys/ioctl.h> | |
#include <netinet/in.h> | |
#include <net/if.h> | |
#include <arpa/inet.h> | |
int main(int argc, char *argv[]) | |
{ | |
int fd; | |
struct ifreq ifr; | |
const char *interface = argc > 1 ? argv[1] : "eth0"; | |
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, interface, 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