您的位置:首页 > 理论基础 > 计算机网络

获取局域网中网络用户名、IP以及MAC

2016-05-31 00:00 330 查看
#include <Winsock2.h>
#include <Iphlpapi.h>
#include <tchar.h>
#include <atlstr.h>
#include <WS2tcpip.h>
#include <iostream>
#include "stdafx.h"
#pragma comment( lib,"Ws2_32.lib" )
#pragma comment( lib,"Mpr.lib" )
#pragma comment( lib,"iphlpapi.lib" )

using namespace std;
char* GetRemoteMAC(char IP[])
{
HRESULT hr;
IPAddr ipAddr;
ULONG pulMac[2];
ULONG ulLen;

CString tmp0;
CString tmp1;
char* strMac = new char[20];
char strIP[20];

inet_pton(AF_INET, IP, (void *)&ipAddr);
memset(pulMac, 0xff, sizeof(pulMac));
ulLen = 6;
hr = SendARP(ipAddr, 0, pulMac, &ulLen);
if (NO_ERROR != hr || ulLen == 0) return "";

ULONG i;
PBYTE pbHexMac = (PBYTE)pulMac;

// Convert the binary MAC address into human-readable
for (i = 0; i < ulLen - 1; ++i) {
tmp0.Format("%02X:", pbHexMac[i]);
tmp1 += tmp0;
}
tmp0.Format("%02X", pbHexMac[i]);
tmp1 += tmp0;
//printf("%s\t", tmp1);
strncpy(strMac, tmp1.GetBuffer(tmp1.GetLength()), 20);
//printf("%s\t", strMac);
//memset(strMac, 0, sizeof(strMac));
return strMac;
}

void main()
{
DWORD dwScope = RESOURCE_CONTEXT;
NETRESOURCE *NetResource = NULL;
HANDLE hEnum;
WSADATA wsaData;

struct hostent *host;
struct in_addr *ptr;

char IP[20];
char *strMacr;

// Initialize Windows Socket Library.
WSAStartup(MAKEWORD(1, 1), &wsaData);

WNetOpenEnum(dwScope, NULL, NULL, NULL, &hEnum);

if (hEnum) {
DWORD Count = 0xFFFFFFFF;
DWORD BufferSize = 10240;
LPVOID Buffer = new char[10240];

WNetEnumResource(hEnum, &Count, Buffer, &BufferSize);
NetResource = (NETRESOURCE *)Buffer;

for (unsigned int i = 0; i < Count; i++, NetResource++) {
if (NetResource->dwUsage == RESOURCEUSAGE_CONTAINER && NetResource->dwType == RESOURCETYPE_ANY) {
if (NetResource->lpRemoteName) {

CString strFullName = NetResource->lpRemoteName;
if (0 == strFullName.Left(2).Compare("\\\\")) strFullName = strFullName.Right(strFullName.GetLength() - 2);

// Get Host
host = gethostbyname(strFullName);
if
7fe0
(host == NULL) continue;
ptr = (struct in_addr *)host->h_addr_list[0];

// Get IP
int a = ptr->S_un.S_un_b.s_b1;
int b = ptr->S_un.S_un_b.s_b2;
int c = ptr->S_un.S_un_b.s_b3;
int d = ptr->S_un.S_un_b.s_b4;

printf("[IP]\t");
sprintf(IP, "%d.%d.%d.%d\t" , a, b, c, d);
for (int n = strlen(IP); n < 20; n++)
{
IP
= '\0';
}
printf("%s\t", IP);
strMacr = GetRemoteMAC(IP);
if (strMacr != "")
{
printf("[MAC]\t%s\t[HOST]\t%s\n", strMacr, strFullName);

}
else
{
printf("[MAC]\tUable to get!\t[HOST]\t%s\n", strFullName);
}

}
}
}

delete Buffer;

WNetCloseEnum(hEnum);
}

WSACleanup();
system("pause");
}

网上学习到的,有些IP获取不到MAC,不知道咋整哎
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IP MAC