gethostbyname获取本机IP

来源:互联网 发布:苏宁秒杀软件哪个好 编辑:程序博客网 时间:2024/05/03 20:20
#include <winsock2.h>#include <stdio.h>#pragma comment(lib, "WS2_32")int main(void){WSADATA wsaData;WORD sockVersion = MAKEWORD(2,0);WSAStartup(sockVersion, &wsaData);char szHost[256];// 取得本地主机名称gethostname(szHost, 256);// 通过主机名得到地址信息hostent *pHost = ::gethostbyname(szHost);// 打印出所有IP地址in_addr addr;for(int i = 0; ; i++){char *p = pHost->h_addr_list[i];if(p == NULL)break;memcpy(&addr.S_un.S_addr, p, pHost->h_length);char *szIp = ::inet_ntoa(addr);printf(" 本机IP地址:%s  \n ", szIp);}WSACleanup();return 0;}

0 0