1. 程式人生 > >獲取指定網絡卡對應的IP地址

獲取指定網絡卡對應的IP地址

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <sys/socket.h>
 4 #include <sys/types.h>
 5 #include <sys/ioctl.h>
 6 #include <net/if.h>
 7 // #include <netinet/in.h>
 8 #include <arpa/inet.h>
 9 // #include <ifaddrs.h>
10 
11 #define IF_NAME   "eth0"
12
13 int main(void) 14 { 15 struct ifreq ifr; 16 int skfd = 0; 17 static char if_addr[16]; 18 19 if ((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { 20 } 21 22 strcpy(ifr.ifr_name, IF_NAME); 23 if (ioctl(skfd, SIOCGIFADDR, &ifr) < 0) { 24 close(skfd); 25 }
26 strcpy(if_addr, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); 27 printf("ipaddr : %s\n", if_addr); 28 close(skfd); 29 30 }