[MFC] Cum aflu IP-urile din sistem ?

Despre MFC, ATL si alte biblioteci C++ de la Microsoft (forum moderat)
Post Reply
mesajflaviu
Membru++
Membru++
Posts: 684
Joined: 10 Sep 2008, 21:40
Judet: Cluj

[MFC] Cum aflu IP-urile din sistem ?

Post by mesajflaviu » 26 Jul 2012, 19:56

Intrebare
Cum pot afla IP-urile din sistem ?
Raspuns
Pentru IP-ul local si IP-ul de retea se foloseste functia GetIpAddrTable, ca in exemplul de mai jos :

Code: Select all

int CMyClass::FindLocalAddress(CStringArray& saIP)
{
	struct in_addr inAddr;
	PMIB_IPADDRTABLE ipAddr;
	char chData[sizeof(MIB_IPADDRTABLE) + 32 * sizeof(MIB_IPADDRROW)];
	ULONG ulLength = sizeof(chData);

	if(NO_ERROR == GetIpAddrTable((PMIB_IPADDRTABLE)chData, &ulLength, TRUE))
	{
		ipAddr = (PMIB_IPADDRTABLE)chData;
		for(int i = 0;i < (int)ipAddr->dwNumEntries;++i)
		{
			if(0 != ipAddr->table[i].dwAddr)
			{
				memmove(&inAddr, &(ipAddr->table[i].dwAddr), 4);
				saIP.Add(inet_ntoa(inAddr));
			}
		}
	}

	return saIP.GetSize();
}
in parametrul referinta saIP de tip CStringArray& vom avea IP-urile locale si de retea.

Pentru a afla IP-ul web se foloseste adresa web care returneaza o pagina web ce contine IP-ul cerut. Un exemplu de implementare este mai jos :

Code: Select all

BOOL CMyClass::FindWebAddress(CString& sIP)
{
	CString sTemp;
	BOOL bRet = FALSE;
	CInternetSession ISession;
	CInternetFile* pIFile = NULL;

	try
	{
		pIFile = (CInternetFile*)ISession.OpenURL(_T("http://checkip.dyndns.org"),1,INTERNET_FLAG_TRANSFER_ASCII | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD);
		if(! pIFile)AfxThrowMemoryException();
		while(pIFile->ReadString(sTemp))sIP += sTemp;
	}
	catch(CInternetException* pInternetException)
	{
		pInternetException->GetErrorMessage(sTemp.GetBuffer(255),255);
		sTemp.ReleaseBuffer();
		pInternetException->Delete();
	}
	catch(CException* pException)
	{
		pException->GetErrorMessage(sTemp.GetBuffer(255),255);
		sTemp.ReleaseBuffer();
		pException->Delete();
	}

	if(pIFile)
	{
		pIFile->Close();
		delete pIFile;
	}

	ISession.Close();

	sIP.MakeLower();
	CString sToken(_T("current ip address"));
	int nIndex = sIP.Find(sToken);
	if(-1 != nIndex)
	{
		int nIndex2 = sIP.Find('<',nIndex);
		if(-1 != nIndex2 && nIndex2 > nIndex)
		{
			nIndex += sToken.GetLength() + 1;
			sTemp = sIP.Mid(nIndex,nIndex2 - nIndex);
			sTemp.TrimLeft();sTemp.TrimRight();
			sIP = sTemp;
			bRet = TRUE;
		}
	}

	return bRet;
}
in parametrul referinta sIP de tip CString& se afla IP-ul web.

Resurse
<< Back to MFC index



Post Reply