1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| #include <winsock2.h> #include <iphlpapi.h> #define HAVE_REMOTE #include "pcap.h" #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "iphlpapi.lib") #pragma comment(lib, "wpcap.lib")
char g_szSubMask[20] = { 0 }; char g_szAdapter[40] = { 0 };
BOOL GetCardAdapter() { ULONG size = 0; ULONG ret = GetAdaptersInfo(NULL, &size); if (ret != ERROR_BUFFER_OVERFLOW) return FALSE; PIP_ADAPTER_INFO iai = (PIP_ADAPTER_INFO)malloc(size); if (iai == NULL) return FALSE; memset(iai, 0, size); ret = GetAdaptersInfo(iai, &size); if (ret != ERROR_SUCCESS) { free(iai); return FALSE; } PIP_ADAPTER_INFO iaitemp = iai; while (iaitemp != NULL) { if (strcmp(iaitemp->IpAddressList.IpAddress.String, "0.0.0.0") != 0) { strcpy_s(g_szSubMask, 20, iaitemp->IpAddressList.IpMask.String); strcpy_s(g_szAdapter, 40, iaitemp->AdapterName); free(iai); return TRUE; } iaitemp = iaitemp->Next; } free(iai); return FALSE; }
BOOL CapturePacket() { if (!GetCardAdapter()) return FALSE; bpf_program fcode = { 0 }; char szDevName[128] = { 0 }; char errbuf[PCAP_ERRBUF_SIZE] = { 0 }; sprintf_s(szDevName, "rpcap://\\Device\\NPF_%s", g_szAdapter); pcap_t *handle = pcap_open(szDevName, 65536, FALSE, 1000, NULL, errbuf); if (handle == NULL) return FALSE; unsigned int nMask = inet_addr(g_szSubMask); if (nMask == INADDR_ANY) nMask = INADDR_NONE; if (pcap_compile(handle, &fcode, "ip and tcp", 1, nMask) < 0) { pcap_close(handle); return FALSE; } if (pcap_setfilter(handle, &fcode) < 0) { pcap_close(handle); return FALSE; } int nLen = 0; pcap_pkthdr *head = NULL; const u_char *pktdata = NULL; DWORD dwTick = GetTickCount(); while ((GetTickCount() - dwTick) < 5000) { Sleep(1); nLen = pcap_next_ex(handle, &head, &pktdata); if (nLen < 1) continue; } pcap_close(handle); return FALSE; }
|