获取IP地址并返回Cstring
CString CAddStdDlg::GetLocalIP() { WSADATA wsaData; int err = WSAStartup(MAKEWORD(2, 0), &wsaData); if (err != 0) { return _T(""); } char szHostName[MAX_PATH] = { 0 }; int nRetCode; nRetCode = gethostname(szHostName, sizeof(szHostName)); char* lpLocalIP; PHOSTENT hostinfo; if (nRetCode != 0) { WSACleanup(); return _T(""); } hostinfo = gethostbyname(szHostName); lpLocalIP = inet_ntoa(*(struct in_addr*) * hostinfo->h_addr_list); CString aa(lpLocalIP); WSACleanup(); return aa; }
void CMyDlg::GetHostAddress(CString &strIPAddr) { char HostName[100]; gethostname(HostName, sizeof(HostName));// 获得本机主机名. hostent* hn; hn = gethostbyname(HostName);//根据本机主机名得到本机ip strIPAddr=inet_ntoa(*(struct in_addr *)hn->h_addr_list[0]);//把ip换成字符串形式 } //摘自 https://blog.csdn.net/imxiangzi/article/details/38264563
代码没有问题,在使用的时候 报错
warning C4996: 'gethostbyname': Use getaddrinfo() or GetAddrInfoW() instead or define _WINSOCK_DEPRECATED_NO_WARNINGS to disable deprecated API
这是因为新版本VS不支援该函数,需要修改下图中SDL检查 为 “否”