gethostname函数
下面的代码是获取我的计算机名称,需要注意的时候,调用gethostname函数之前,必须调用WSAStartup函数才行

#pragma comment(lib,"ws2_32.lib")
#include <winsock.h>
#include <iostream>

int main()
{
WSADATA wsData;
WORD version=2;// 2是我随便写的
WSAStartup(version,&wsData);
char host_name[128];// 128足够长,可以装下我的计算机名称
gethostname(host_name, 128);
printf("%s\n", host_name);//打印计算机名称
}

gethostbyname函数
下面的代码是通过计算机名称,获取IP,需要注意有一个inet_ntoa函数,该函数是将十进制网络字节序转换为点分十进制IP格式,如果不用该函数,那么将无法正确打印出IP

#pragma comment(lib,"ws2_32.lib")
#include <winsock.h>
#include <iostream>

char* getHostName() {
WSADATA wsData;
WORD version = 2;// 2是我随便写的
WSAStartup(version, &wsData);
char* p_host_name = new char[128];
gethostname(p_host_name, 128);
return p_host_name;
}

int main()
{
char * hostName = getHostName();
struct hostent * hostnet=gethostbyname(hostName);
char ** pIpList=hostnet->h_addr_list;
for (int i = 0; hostnet->h_addr_list[i]; i++) {
printf("%s\n", inet_ntoa(*(struct in_addr*)hostnet->h_addr_list[i]));
}
}