在C中查找机器的IP地址? [英] Find IP address of the machine in C?

查看:425
本文介绍了在C中查找机器的IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Windows上以C语言获取本地计算机的IP地址?我无法通过以下代码获取我的机器的IP地址:

How do I get the IP address of the local machine in C on Windows? I was not able to get the IP address of my machine in the following code:

#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;
}

我在编译时遇到错误:


致命错误C1083:无法打开包含文件:'net / if.h':没有这样的文件或目录。

fatal error C1083: Cannot open include file: 'net/if.h': No such file or directory.

我不能使用 #include< net / if.h> ,因为它只能在Linux上使用。

I cannot use #include <net/if.h> as it is only available on Linux.

推荐答案

您展示的代码无法编译,因为它是专为Linux设计的,而不是Windows。 Windows上没有< net / if.h> 标题。

The code you showed does not compile because it is designed for Linux, not Windows. There is no <net/if.h> header on Windows.

getifaddrs() 返回链接本地接口地址列表。但是,Windows上根本不存在 getifaddrs()(除非您找到自定义的第三方实现)。

getifaddrs() returns a linked list of local interface addresses. But getifaddrs() does not exist on Windows at all (unless you find a custom 3rd party implementation).

Windows上的等效内容是使用Win32 XP及更早版本的GetAdaptersInfo() 功能,或 GetAdaptersAddresses() 。这两个函数都返回一个详细的适配器信息的链接列表(不仅仅是地址)。

The equivalent on Windows is to use the Win32 GetAdaptersInfo() function on XP and earlier, or the GetAdaptersAddresses() function on Vista and later. Both functions return a linked list of detailed adapter information (much more than just addresses).

在MSDN上的文档中提供了C示例。

C examples are provided in their documentation on MSDN.

这篇关于在C中查找机器的IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆