close

這邊文章的重點只有三個,
第一是取得IP、第二是取得MAC、第三是解決symbol inet_ntop referenced in function的問題。

廢話不多說,我們直接上Code ,
最近忙跟人交接,實在沒辦法太精緻打文章。
 




#include 
 
/*#include */

#include <winsock2.h>
#include <windows.h>
#include <Iphlpapi.h>
#include <algorithm>
#include <ws2ipdef.h>
#include <WS2tcpip.h>
#pragma comment(lib, "IPHLPAPI.lib")
#pragma comment(lib, "ws2_32.lib") //symbol inet_ntop referenced in function


#define BUFF_LEN			256*2
using namespace std;




void displayAddress(const SOCKET_ADDRESS &Address)
{
	cout << "\n  Length of sockaddr: " << Address.iSockaddrLength;
	if (Address.lpSockaddr->sa_family == AF_INET)
	{
		sockaddr_in *si = (sockaddr_in *)(Address.lpSockaddr);
		char a[INET_ADDRSTRLEN] = {};
		if (inet_ntop(AF_INET, &(si->sin_addr), a, sizeof(a)))
			cout << "\n   IPv4 address: " << a;
	}
	else 
	if (Address.lpSockaddr->sa_family == AF_INET6)
	{
		sockaddr_in6 *si = (sockaddr_in6 *)(Address.lpSockaddr);
		char a[INET6_ADDRSTRLEN] = {};
		if (inet_ntop(AF_INET6, &(si->sin6_addr), a, sizeof(a)))
			cout << "\n   IPv6 address: " << a;
	}
}



int main()
{
	ULONG		nFlags = 0;
	int			nCount = 0;
	TCHAR		wzInterfaceName[BUFF_LEN];
	// during system initialization, GetAdaptersAddresses may return ERROR_BUFFER_OVERFLOW and supply nLen,
	// but in a subsequent call it may return ERROR_BUFFER_OVERFLOW and supply greater nLen !
	ULONG nLen = sizeof(IP_ADAPTER_ADDRESSES);
	BYTE* pBuf = NULL;
	DWORD nErr = 0;

	do 
	{
		delete[] pBuf;
		pBuf = new BYTE[nLen];
		nErr = ::GetAdaptersAddresses(AF_INET, nFlags, NULL, (IP_ADAPTER_ADDRESSES*&)pBuf, &nLen);

	} while (ERROR_BUFFER_OVERFLOW == nErr);

	if (NO_ERROR != nErr)
	{
		delete[] pBuf;
		return 0;
	}

	const IP_ADAPTER_ADDRESSES* pAdaptersAddresses = (IP_ADAPTER_ADDRESSES*&)pBuf;
	
	while (pAdaptersAddresses)// for each adapter
	{
		TCHAR wzBuf[BUFF_LEN];
		ZeroMemory(wzBuf, BUFF_LEN);

		MultiByteToWideChar
		(
			CP_UTF8,
			0,
			pAdaptersAddresses->AdapterName,
			-1,
			wzBuf,
			BUFF_LEN
		);
		lstrcpy(wzInterfaceName, pAdaptersAddresses->Description);
		nCount++;
		const IF_OPER_STATUS& Stat = pAdaptersAddresses->OperStatus;//1:up,2:down
		
		PIP_ADAPTER_UNICAST_ADDRESS pu = pAdaptersAddresses->FirstUnicastAddress;
		displayAddress(pu->Address);
		
		pAdaptersAddresses = pAdaptersAddresses->Next;
	}
	cout << "Count : " << nCount << endl;
}


 

結果 :

image

 

 

arrow
arrow
    創作者介紹
    創作者 Eric 的頭像
    Eric

    一個小小工程師的心情抒發天地

    Eric 發表在 痞客邦 留言(0) 人氣()