VC获取主机名与外网IP(CString类型)时间:2021-04-14 13:34:17 前一章节提到的,在VC下动态获取主机名与外网IP地址,有兴趣的可以看看! /************************************************************************/ /* 函数说明:获取当前外网IP地址 /* 参 数:无 /* 返 回 值:返回外网IP地址、CString类型字符串 /* By:Koma 2009.08.21 14:12 /************************************************************************/ CString CQDlg::GetIPAddress() { char buf[MAX_PATH] = {0}; char chTempIp[128]; char chIP[64]; CString strPath; strPath = GetExePath() + "//netip.ini"; URLDownloadToFile(0,"http://www.ip138.com/ip2city.asp",strPath,0,NULL); FILE *fp=fopen( strPath, "r" ); if ( fp != NULL ) { fseek(fp, 0, SEEK_SET); fread(buf,1,256,fp); fclose(fp); char* iIndex = strstr(buf,"["); if (iIndex) { sprintf( chTempIp,"%s",iIndex); int nBuflen = strlen(chTempIp); for(int i =0; i<nBuflen; i++) { chIP[i] = chTempIp[i+1]; if(chTempIp[i] == ']') { chIP[i-1] = '/0'; DeleteFile(strPath); continue; } } } } CString strTemp=""; if(chIP != "") { strTemp.Format("%s",chIP); } return strTemp; } /************************************************************************/ /* 函数说明:获取当前主机名 /* 参 数:无 /* 返 回 值:返回主机名、CString类型字符串 /* By:Koma 2009.08.21 14:23 /************************************************************************/ CString CQDlg::GetHostName() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2,0); err = WSAStartup(wVersionRequested,&wsaData); if(err != 0) { return err; } if(LOBYTE(wsaData.wVersion != 2) || HIBYTE(wsaData.wVersion) != 0) { WSACleanup(); return (char)WSAVERNOTSUPPORTED; } char szHostName[256]; int nRetCode; CString str=""; //调用API来获得主机名 nRetCode = gethostname(szHostName,sizeof(szHostName)); if(nRetCode != 0) { return WSAGetLastError(); } if(szHostName != "") { str.Format("主机名:%s",szHostName); } return str; }