Get the IP address of a network interface in C using SIOCGIFADDR

int get_gw_ip(char *eth, char *ipaddr)
{
 int sock_fd;
 struct  sockaddr_in my_addr;
 struct ifreq ifr;

 /**//* Get socket file descriptor */
 if ((sock_fd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
 {
  perror("socket");
  return RET_FAILED;
 }

 /**//* Get IP Address */
 strncpy(ifr.ifr_name, eth, IF_NAMESIZE);
 ifr.ifr_name[IFNAMSIZ-1]='/0';

 if (ioctl(sock_fd, SIOCGIFADDR, &ifr) < 0)
 {
  DBGPRN(":No Such Device %s/n",eth);
  return RET_FAILED;
 }

 memcpy(&my_addr, &ifr.ifr_addr, sizeof(my_addr));
 strcpy(ipaddr, inet_ntoa(my_addr.sin_addr));
 close(sock_fd);
 return RET_SUCCESS;
}

其中 eth是网卡名字 如“eth0” “eth1”等,ipaddr是输出参数


The following header files are needed when using this method:
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>

In addition, this particular implementation makes use of:

#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>

你可能感兴趣的:(Get the IP address of a network interface in C using SIOCGIFADDR)