根据网卡(eth0, eth1)获得对应的IP地址

核心是利用 ioctl函数的SIOCGIFADDR 来获取


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

 if ((sock_fd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
  perror("socket");
  return RET_FAILED;
 }

 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;
}




你可能感兴趣的:(TCP/IP网络编程)