sockaddr_in addr;
char hostname[MAX_PATH]; gethostname(hostname,MAX_PATH);
hostent *ht = NULL;
ht = ::gethostbyname(hostname);
if(ht != NULL)
memcpy(&addr, ht->h_addr_list[0],sizeof(sockaddr_in));char ip[16];
strcpy(ip,inet_ntoa(addr.sin_addr));我通过交换机上网的,设置的内网IP是192.168.0.211,得到的却是一个外网IP:56.100.56.48,那怎样才能获得192.168.0.211?
char hostname[MAX_PATH]; gethostname(hostname,MAX_PATH);
hostent *ht = NULL;
ht = ::gethostbyname(hostname);
if(ht != NULL)
memcpy(&addr, ht->h_addr_list[0],sizeof(sockaddr_in));char ip[16];
strcpy(ip,inet_ntoa(addr.sin_addr));我通过交换机上网的,设置的内网IP是192.168.0.211,得到的却是一个外网IP:56.100.56.48,那怎样才能获得192.168.0.211?
const long lBufSize = 4096;
//command line string
char szFetCmd[] = "ipconfig /all"; //Search string
string str4Search = "IP Address. . . . . . . . . . . . : ";
CString strBeg = "ordinal hint RVA name";
CString strEnd = "Summary";
CString strRet = _T("");
BOOL bRet;
SECURITY_ATTRIBUTES sa;
HANDLE hReadPipe,hWritePipe; //Init
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
//Create pipe
bRet = CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
if(FALSE == bRet)
{
return strRet;
} //Get infomation
STARTUPINFO si;
PROCESS_INFORMATION pi; si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si); si.hStdError = hWritePipe;
si.hStdOutput = hWritePipe;
//si.wShowWindow = SW_HIDE; //Hide command windows
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
//Create command process
bRet = CreateProcess (NULL, szFetCmd, NULL, NULL, TRUE, 0, NULL,
NULL, &si, &pi );
char szBuffer[lBufSize + 1];
string strBuffer;
if (TRUE == bRet)
{
WaitForSingleObject (pi.hProcess, INFINITE);
//Read infomation
unsigned long count;
memset(szBuffer, 0x00, sizeof(szBuffer));
bRet = ReadFile(hReadPipe, szBuffer, lBufSize, &count, 0);
if(TRUE == bRet)
{ strBuffer = szBuffer; CString strBuf(szBuffer);
int nBegPos = strBuf.Find(strBeg);
int nEndPos = strBuf.Find(strEnd); strBuf = strBuf.Mid( nBegPos,nEndPos - nBegPos );
long ipos;
ipos = strBuffer.find(str4Search); //Get adress infomation
strBuffer = strBuffer.substr(ipos+str4Search.length());
ipos = strBuffer.find("\n");
strBuffer = strBuffer.substr(0, ipos);
strRet.Format("%s", strBuffer.c_str());
//strRet.Remove('-'); strRet = strRet.Left(strRet.GetLength() - 2 );
}
}
//close handle
CloseHandle(hWritePipe);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hReadPipe);
cout<<"\n无法获取主机!\n ";
cout << "MachineName: " << chInfo << endl; hostent *hostentaddr = gethostbyname(chInfo);
string abc = inet_ntoa(*((struct in_addr*)hostentaddr->h_addr_list[0]));
cout << "MachineIPAddress: " << abc << endl;
gethostname(HostName,sizeof(HostName)); //得到主机名
hostent *p; //定义hostent(是个系统预定义的结构体)类型的指针
char *p2; //定义字符指针
p=gethostbyname(HostName);
p2=inet_ntoa(*((in_addr *)p->h_addr)); //得到IP地址
puts("本机ip地址");
puts(p2); //输出ip地址