//获得[本机IP]------------------------------301---[begin]
char szText[256];
//获取本机主机名称
int iRet;
iRet = gethostname(szText, 256);
int a = WSAGetLastError();
if (iRet != 0)
{
printf("gethostname() Failed!");
return;
}
//通过主机名获取到地址信息
HOSTENT *host = gethostbyname(szText);
if (NULL == host)
{
printf("gethostbyname() Failed!");
return;
}
in_addr PcAddr;
for (int i = 0;; i++)
{
char *p = host->h_addr_list[i];
if (NULL == p)
{
break;
}
memcpy(&(PcAddr.S_un.S_addr), p, host->h_length);
char*szIP = ::inet_ntoa(PcAddr);
printf("本机的ip地址是:%s\n", szIP);
short ip_lenth=0;
ip_lenth = strlen(szIP);
memcpy(local_IP, szIP, ip_lenth);
printf("length:%d\n", ip_lenth);
}
//获得[本机IP]------------------------------301---[end]
C++获得本地机IP(windows下 VS环境)
最新推荐文章于 2022-03-24 15:38:17 发布