English 中文(简体)
C 获取IP地址的守则
原标题:C code to get the IP address
  • 时间:2009-10-15 05:52:12
  •  标签:

我如何利用C码获得当地机器的IP地址?

如果存在多个接口,我就应当能够展示每个接口的IP地址。

<>光> 在C法典中不使用任何指令,如config,以检索IP地址。

最佳回答
问题回答
#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
", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

    close(fd);
}

如果你要列举所有接口,请看getifaddrs()的功能——如果你重新回到了短链氯化石蜡。

了解“proc/net/dev”的所有接口。 注:它不能只使用电离线进行所有接口。

#define PROC_NETDEV "/proc/net/dev"

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

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

然后用电线(Octl)():

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. */
}




相关问题
热门标签