C 编程 : Getting Windows IP Address

标签 c windows

我是 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() (or popen()) can be a security risk since certain environment variables (like $IFS / $PATH) can be modified so that your program will execute external programs you never intended it to (i.e. a command is specified without a path name and the command processor path name resolution mechanism is accessible to an attacker).

Also the system() function can result in exploitable vulnerabilities:

  • when passing an unsanitized or improperly sanitized command string originating from a tainted source;
  • if a relative path to an executable is specified and control over the current working directory is accessible to an attacker;
  • if the specified executable program can be spoofed by an attacker.

这是我使用 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 地址。谢谢

最佳答案

您可以使用 IpHlpApi Module .微软提供Ipconfig sample code其中演示了如何使用 IP Helper API GetNetworkParams() 和 GetAdaptersInfo()。这是 Windows 经典示例 Ipconfig 解决方案。

或者你可以使用 getaddrinfo .

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

关于C 编程 : Getting Windows IP Address,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216004/

相关文章:

c - C 中的是/否循环

python - 使用共享内存从单独的 C 进程访问 numpy 数组

windows - ZMQ::LibZMQ3 和草莓 perl

windows - 双模式可执行吗?

c++ - cl.exe 在哪里? (MS 构建工具 '13)

python - 如何正确设置 python/c 库?

c - 以用户身份编程 I/O 端口

c - 我想打开新的 cmd 提示符并从 cmd 提示符插入参数

linux - 使用 SSHFS 在 Windows 10 中挂载 Linux FS

Windows 关机 - 关机命令或 ExitWindowsEx