2009-10-15 130 views
2

如何使用C代码获取本地计算机的IP地址?获取IP地址的C代码

如果有多个接口,那么我应该能够显示每个接口的IP地址。

注意:不要使用任何命令如ifconfig在C代码中检索IP地址。

+2

家庭作业?你到目前为止有什么? – GManNickG 2009-10-15 05:54:14

+0

您必须注意,在使用'ifconfig'的生产代码中不是最糟糕的解决方案。 – 2009-10-15 06:15:34

+0

不要担心这不是我的家庭作业难题....我越来越多地参与到一些在C中的严重编程,结果试图修复我的应用程序中的一些缺失的链接.... – codingfreak 2009-10-15 07:22:13

回答

3

Michael Foukarakis我能够显示各种接口在同一台机器上的IP地址输入:

#include <arpa/inet.h> 
#include <sys/socket.h> 
#include <netdb.h> 
#include <ifaddrs.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 

int 
main(int argc, char *argv[]) 
{ 
    struct ifaddrs *ifaddr, *ifa; 
    int family, s; 
    char host[NI_MAXHOST]; 

    if (getifaddrs(&ifaddr) == -1) { 
     perror("getifaddrs"); 
     exit(EXIT_FAILURE); 
    } 

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { 
     family = ifa->ifa_addr->sa_family; 

     if (family == AF_INET) { 
      s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), 
              host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); 
      if (s != 0) { 
       printf("getnameinfo() failed: %s\n", gai_strerror(s)); 
       exit(EXIT_FAILURE); 
      } 
      printf("<Interface>: %s \t <Address> %s\n", ifa->ifa_name, host); 
     } 
    } 
    return 0; 
} 
10
#include <stdio.h> 
#include <string.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <sys/ioctl.h> 
#include <netinet/in.h> 
#include <net/if.h> 

int main() 
{ 
    int fd; 
    struct ifreq ifr; 

    fd = socket(AF_INET, SOCK_DGRAM, 0); 

    ifr.ifr_addr.sa_family = AF_INET; 

    snprintf(ifr.ifr_name, IFNAMSIZ, "eth0"); 

    ioctl(fd, SIOCGIFADDR, &ifr); 

    /* and more importantly */ 
    printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); 

    close(fd); 
} 

如果要列举所有的接口,看看在getifaddrs()功能 - 如果你是在Linux上。

-1

获取“/ proc/net/dev”中的所有接口。注意:它不能仅使用ioctl获取所有接口。

#define PROC_NETDEV "/proc/net/dev" 

fp = fopen(PROC_NETDEV, "r"); 
while (NULL != fgets(buf, sizeof buf, fp)) { 
    s = strchr(buf, ':'); 
    *s = '\0'; 
    s = buf; 

    // Filter all space ' ' here 
    got one interface name here, continue for others 
} 
fclose(fp); 

然后获得使用地址的ioctl():

struct ifreq ifr; 
struct ifreq ifr_copy; 
struct sockaddr_in *sin; 

for each interface name { 
    strncpy(ifr.ifr_name, ifi->name, sizeof(ifr.ifr_name) - 1); 
    ifr_copy = ifr; 
    ioctl(fd, SIOCGIFFLAGS, &ifr_copy); 
    ifi->flags = ifr_copy.ifr_flags; 
    ioctl(fd, SIOCGIFADDR, &ifr_copy); 
    sin = (struct sockaddr_in*)&ifr_copy.ifr_addr; 
    ifi->addr = allocating address memory here 
    bzero(ifi->addr, sizeof *ifi->addr); 
    *(struct sockaddr_in*)ifi->addr = *sin; 

    /* Here also you could get netmask and hwaddr. */ 
} 
+0

看到其他职位如何打开“fd” – Test 2009-10-15 06:07:35