本文主要是介绍VC获取本机IP地址列表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
来源:http://www.2cto.com/kf/201102/83560.html
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
int doit(int, char **)
{
char host_name[255];
//获取本地主机名称
if (gethostname(host_name, sizeof(host_name)) == SOCKET_ERROR) {
printf("Error %d when getting local host name. ", WSAGetLastError());
return 1;
}
printf("Host name is: %s ", host_name);
//从主机名数据库中得到对应的“主机”
struct hostent *phe = gethostbyname(host_name);
if (phe == 0) {
printf("Yow! Bad host lookup.");
return 1;
}
//循环得出本地机器所有IP地址
for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
struct in_addr addr;
memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
printf("Address %d : %s " , i, inet_ntoa(addr));
}
return 0;
}
int main(int argc, char *argv[])
{
WSAData wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
return 255;
}
int retval = doit(argc, argv);
WSACleanup();
return retval;
}
这篇关于VC获取本机IP地址列表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!