本文介绍了获取IP地址的C代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I get the IP address of the local machine using C code?

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

If there are multiple Interfaces then I should be able to display the IP address of each interface.

注意:请勿在 C 代码中使用 ifconfig 等任何命令来检索 IP 地址.

NOTE: Do not use any commands like ifconfig within C code to retrieve the IP address.

推荐答案

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

With the inputs from Michael Foukarakis I am able to show the IP address for various interfaces on the same machine:

#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
", gai_strerror(s));
                exit(EXIT_FAILURE);
            }
            printf("<Interface>: %s 	 <Address> %s
", ifa->ifa_name, host);
        }
    }
    return 0;
}

这篇关于获取IP地址的C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:01