C example to getting IP address from a network interface, run on Raspberry Pi/Raspbian Jessie.
Reference: http://www.geekpage.jp/en/programming/linux-network/get-ipaddr.php
cIP.c
#include <stdio.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>
/*
* Getting IP address from a network interface
* reference: http://www.geekpage.jp/en/programming/linux-network/get-ipaddr.php
*
*/
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;
}
Related:
- Java code to listing Network Interface Addresses, run on Raspberry Pi/Raspbian Jessie
- Python code to find my IP address, run on Raspberry Pi/Raspbian Jessie
No comments:
Post a Comment