Saturday, December 4, 2010

Getting IP address from a network interface in Linux in C


//code for Getting IP address from a network interface
//compile gcc ip.c
//this code: ip.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>

int main()
{
 int fd;

//ifreq - Network: Defines an interface request for socket ioctl commands
 struct ifreq ifr;
//socket - create an endpoint for communication
//int socket(int domain, int type, int protocol);
/*
AF_INET address family sockets can be either connection-oriented (type SOCK_STREAM)
or they can be connectionless (type SOCK_DGRAM). Connection-oriented AF_INET sockets
use TCP as the transport protocol. Connectionless AF_INET sockets use UDP as the transport protocol.
*/
 fd = socket(AF_INET, SOCK_DGRAM, 0);

 /* IPv4 IP address */
 ifr.ifr_addr.sa_family = AF_INET;

 /* I want IP address attached to "eth0" */
//char *strncpy(char *s1, const char *s2, size_t n);
//strncpy - copy part (n char) of a string s2 to s1

 strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
//*int ioctl(int d, int request, ...);   //ioctl - control device
  ioctl(fd, SIOCGIFADDR, &ifr) where fd is the file descriptor of the socket, and &ifr is the address of the struct ifreq object.
The return from the ioctl call is -1 on failure or 0 on success.
SIOCGIFADDR - get interface address
*/
ioctl(fd, SIOCGIFADDR, &ifr);
 close(fd);
/*On success, you can cast the ifr_addr address to the socket address type for the chosen address family (eg. cast to sockaddr_in for normal internet ipv4 sockets).
  display result ,
inet_ntoa: returns the dots-and-numbers string in a static buffer
*/
 printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

 return 0;
}

No comments:

Post a Comment