【问题标题】:C Programming: Getting Windows IP AddressC 编程:获取 Windows IP 地址
【发布时间】:2018-03-11 02:18:39
【问题描述】:

我是 C 编程新手,正在尝试编写自己的代码来获取 Microsoft Windows 上的 IP 地址。

我一直在阅读这方面的内容,不幸的是,所有示例都是针对 Linux 而不是 Windows。

参考

  1. C code to get the IP address

  2. Find IP address of the machine in C?

我尝试在所有示例代码中将<sys/socket.h> 替换为Winsock2.h,但在windows 下仍然无法编译。

这些是我在windows下编译时出现的一些错误...

C:\Windows C Programming> gcc get_ip_address.c -o get_ip_address
get_ip_address.c:2:24: fatal error: sys/socket.h: No such file or directory
compilation terminated.

C:\Windows C Programming>

其他错误

fatal error: arpa/inet.h: No such file or directory

fatal error: netdb.h: No such file or directory

fatal error: netdb.h: No such file or directory

fatal error: ifaddrs.h: No such file or directory

顺便说一句,我已经能够使用system() 函数获取 IP。但是根据manlio

system()(或 popen())可能是安全风险,因为某些环境 可以修改变量(如 $IFS / $PATH),以便您的程序 将执行您从未打算执行的外部程序(即 指定的命令没有路径名和命令处理器 攻击者可以访问路径名称解析机制)。

system() 函数也可能导致可利用的漏洞:

  • 在传递源自受污染源的未经处理或处理不当的命令字符串时;
  • 如果指定了可执行文件的相对路径并且攻击者可以访问对当前工作目录的控制;
  • 如果指定的可执行程序可以被攻击者欺骗。

这是我使用system()的代码

C:\Windows C Programming> more ip_address_test.c
#include<stdlib.h>

int main()
{
  system("ipconfig | findstr IPv4");
}

C:\Windows C Programming>

C:\Windows C Programming> gcc ip_address_test.c -o ip_address_test

C:\Windows C Programming>

C:\Windows C Programming> ip_address_test

   IPv4 Address. . . . . . . . . . . : 192.168.1.1
   IPv4 Address. . . . . . . . . . . : 10.1.1.1

C:\Windows C Programming>

请告诉我如何使用 C 编程在 Windows 中获取 IP 地址。谢谢

【问题讨论】:

标签: c windows


【解决方案1】:

您可以使用IpHlpApi Module。 Microsoft 提供了Ipconfig sample code,它演示了如何使用 IP 帮助程序 API GetNetworkParams() 和 GetAdaptersInfo()。这是一个 Windows-classic-samples Ipconfig 解决方案。

您也可以使用getaddrinfo

两个链接都提供了完整的源代码示例来实现您的目标。

【讨论】:

    【解决方案2】:

    使用此代码为您的系统查找 IP 地址

    #include<stdlib.h>
    
    int main()
    {
       system("C:\\Windows\\System32\\ipconfig");
    
       return 0;
    }
    

    我想它会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 2011-07-04
      • 2012-01-09
      • 2021-11-20
      • 2011-08-01
      • 2010-11-04
      • 2011-01-28
      • 1970-01-01
      相关资源
      最近更新 更多