我是 C 编程的新手,正在尝试编写自己的代码以在 Microsoft Windows 上获取 IP 地址。
我一直在阅读这方面的内容,不幸的是所有示例都是针对 Linux 而不是 Windows。
引用
我已经尝试替换 <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/