#pragma warning(disable : 4996)
#include "iostream"
#include "WinSock2.h" //包含winsock库头文件
#include "ws2tcpip.h"
#pragma comment(lib, "ws2_32.lib") //链接winsock导入库
using namespace std;
int main(int argc, char* argv[])
{
int ret;
struct hostent *host;
struct in_addr addr;
//启动socket服务
WSADATA wsaData;
ret = WSAStartup(0x101, &wsaData);
//如果启动成功 ,返回值为0
if (ret != 0)
{
printf("WSAStartup error:%d ", WSAGetLastError());
return 1;
}
//获取主机信息
host = gethostbyname("www.baidu.com");
if (host == NULL)
{
printf("gethostbyname error:%d", WSAGetLastError());
return 1;
}
addr.s_addr = *(unsigned long *)host->h_addr;
printf("主机名 :%s\n", host->h_name);
printf("主机地址: %s\n ", inet_ntoa(addr));
WSACleanup();
return 0;
}
转载https://love.junzimu.com/archives/470
使用的gethostname()函数,但是不支持ipv6,新版中引入了该函数的替换版本getaddrinfo()。