简体   繁体   English

在C中查找机器的IP地址?

[英]Find IP address of the machine in C?

How do I get the IP address of the local machine in C on Windows? 如何在Windows上以C语言获取本地计算机的IP地址? I was not able to get the IP address of my machine in the following code: 我无法在以下代码中获取我的机器的IP地址:

#include <ifaddrs.h>
#include <stdio.h>

int main()
{
    struct ifaddrs *id;
    int val;
    val = getifaddrs(&id);
    printf("Network Interface Name :- %s\n",id->ifa_name);
    printf("Network Address of %s :- %d\n",id->ifa_name,id->ifa_addr);
    printf("Network Data :- %d \n",id->ifa_data);
    printf("Socket Data : -%c\n",id->ifa_addr->sa_data);
    return 0;
}

I am facing an error while compiling: 编译时我遇到错误:

fatal error C1083: Cannot open include file: 'net/if.h': No such file or directory. 致命错误C1083:无法打开包含文件:'net / if.h':没有这样的文件或目录。

I cannot use #include <net/if.h> as it is only available on Linux. 我不能使用#include <net/if.h>因为它只能在Linux上使用。

The code you showed does not compile because it is designed for Linux, not Windows. 您显示的代码无法编译,因为它是为Linux设计的,而不是Windows。 There is no <net/if.h> header on Windows. Windows上没有<net/if.h>标头。

getifaddrs() returns a linked list of local interface addresses. getifaddrs()返回本地接口地址的链接列表。 But getifaddrs() does not exist on Windows at all (unless you find a custom 3rd party implementation). 但是根本不存在Windows上的getifaddrs() (除非您找到自定义的第三方实现)。

The equivalent on Windows is to use the Win32 GetAdaptersInfo() function on XP and earlier, or the GetAdaptersAddresses() function on Vista and later. Windows上的等价物是在XP及更早版本上使用Win32 GetAdaptersInfo()函数,或在Vista及更高版本上GetAdaptersAddresses()函数。 Both functions return a linked list of detailed adapter information (much more than just addresses). 这两个函数都返回详细适配器信息的链接列表(不仅仅是地址)。

C examples are provided in their documentation on MSDN. 它们在MSDN上的文档中提供了C示例。

The structure 结构

struct ifaddrs *id;

is a linked list. 是一个链表。 You have to loop through it and check the existence of the address 你必须遍历它并检查地址是否存在

if(id->fa_addr)
   // print statements

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM