eth_t * eth_open(const char *device) { eth_t *eth; char pcapdev[128]; HANDLE pcapMutex; DWORD wait; if (eth_get_pcap_devname(device, pcapdev, sizeof(pcapdev)) != 0) return (NULL); if ((eth = calloc(1, sizeof(*eth))) == NULL) return (NULL); pcapMutex = CreateMutex(NULL, 0, "Global\\DnetPcapHangAvoidanceMutex"); wait = WaitForSingleObject(pcapMutex, INFINITE); eth->lpa = PacketOpenAdapter(pcapdev); if (wait == WAIT_ABANDONED || wait == WAIT_OBJECT_0) { ReleaseMutex(pcapMutex); } CloseHandle(pcapMutex); if (eth->lpa == NULL) { eth_close(eth); return (NULL); } PacketSetBuff(eth->lpa, 512000); eth->pkt = PacketAllocatePacket(); if (eth->pkt == NULL) { eth_close(eth); return NULL; } return (eth); }
long sockOpen(char *Device) { lpAdapter = PacketOpenAdapter(Device); if (lpAdapter == NULL) return -1; #ifdef DEV9_LOG DEV9_LOG("PacketOpenAdapter %s: %p\n", Device, lpAdapter); #endif if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){ SysMessage("Warning: unable to set promiscuous mode!"); } if(PacketSetBuff(lpAdapter,512000)==FALSE){ SysMessage("Unable to set the kernel buffer!"); return -1; } if(PacketSetReadTimeout(lpAdapter,100)==FALSE){ SysMessage("Warning: unable to set the read tiemout!"); } if((lpRecvPacket = PacketAllocatePacket())==NULL){ SysMessage("Error: failed to allocate the LPPACKET structure."); return (-1); } if((lpSendPacket = PacketAllocatePacket())==NULL){ SysMessage("Error: failed to allocate the LPPACKET structure."); return (-1); } lbytes=0; tbytes=0; return 0; }
//初始化网卡:打开网卡和初始化包结构 int NetworkInterface::InitAdapterCommon(char *adapterName) { //打开网络网卡 adapter.lpAdapter = PacketOpenAdapter(adapterName); if (!adapter.lpAdapter || (adapter.lpAdapter->hFile == INVALID_HANDLE_VALUE)) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Unable to open the adapter!"); return -1; } //分配并初始化一个包结构,将用于接收数据包 if ((adapter.lpPacket = PacketAllocatePacket()) == NULL) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Error: failed to allocate the LPPACKET structure."); return (-1); } //此处分配的动态内存在 PacketClose()中释放 char *buffer = new char[256000]; //256KB PacketInitPacket(adapter.lpPacket,(char*)buffer,256000); //在驱动中设置512K的缓冲区 if (PacketSetBuff(adapter.lpAdapter, 512000) == FALSE) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Unable to set the kernel buffer!"); return -1; } AdapterStat = 1; return 0; }
eth_t * eth_open(const char *device) { eth_t *eth; intf_t *intf; struct intf_entry ifent; eth_addr_t ea; char *p, *buf; ULONG len; /* Get interface entry. */ memset(&ifent, 0, sizeof(ifent)); if ((intf = intf_open()) != NULL) { strlcpy(ifent.intf_name, device, sizeof(ifent.intf_name)); intf_get(intf, &ifent); intf_close(intf); } if (ifent.intf_link_addr.addr_type != ADDR_TYPE_ETH) return (NULL); /* Get Packet driver adapter name/desc lists. */ buf = NULL; PacketGetAdapterNames(buf, &len); if (len > 0 && (buf = malloc(len)) != NULL) { if (!PacketGetAdapterNames(buf, &len)) { free(buf); buf = NULL; } } if (buf == NULL) return (NULL); /* XXX - find adapter with matching interface MAC address. */ if ((eth = calloc(1, sizeof(*eth))) == NULL) { free(buf); return (NULL); } for (p = buf; *p != '\0'; p += strlen(p) + 1) { if ((eth->lpa = PacketOpenAdapter(p)) != NULL) { if (eth->lpa->hFile != INVALID_HANDLE_VALUE && eth_get(eth, &ea) == 0 && memcmp(&ea, &ifent.intf_link_addr.addr_eth, ETH_ADDR_LEN) == 0) { PacketSetBuff(eth->lpa, 512000); eth->pkt = PacketAllocatePacket(); break; } PacketCloseAdapter(eth->lpa); } } free(buf); if (eth->pkt == NULL) eth = eth_close(eth); return (eth); }
/* Set the dimension of the kernel-level capture buffer */ static int pcap_setbuff_win32(pcap_t *p, int dim) { if(PacketSetBuff(p->adapter,dim)==FALSE) { snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer"); return -1; } return 0; }
/* Set the dimension of the kernel-level capture buffer */ static int pcap_setbuff_win32(pcap_t *p, int dim) { struct pcap_win *pw = p->priv; if(PacketSetBuff(pw->adapter,dim)==FALSE) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer"); return (-1); } return (0); }
/* Set the dimension of the kernel-level capture buffer */ int pcap_setbuff(pcap_t *p, int dim) { if (p->adapter==NULL) { snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "The kernel buffer size cannot be set while reading from a file"); return -1; } if(PacketSetBuff(p->adapter,dim)==FALSE) { snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer"); return -1; } return 0; }
eth_t * eth_open(const char *device) { eth_t *eth; char pname[128]; if (intf_get_pcap_devname(device, pname, sizeof(pname)) != 0) return NULL; if ((eth = calloc(1, sizeof(*eth))) == NULL) return (NULL); if ((eth->lpa = PacketOpenAdapter(pname)) == NULL || eth->lpa->hFile == INVALID_HANDLE_VALUE) return (eth_close(eth)); PacketSetBuff(eth->lpa, 512000); if ((eth->pkt = PacketAllocatePacket()) == NULL) return (eth_close(eth)); return (eth); }
bool SniffPacketThread::OpenAdapter(char *theAdapterName) { m_lpa = PacketOpenAdapter(theAdapterName); if(m_lpa == NULL) { TRACE0("PacketOpenAdapter failed"); return(FALSE); } // Allocate packet mem m_lpp = PacketAllocatePacket(); if( m_lpp == NULL) { TRACE0("PacketAllocatePacket failed"); PacketCloseAdapter(m_lpa); return(FALSE); } PacketInitPacket(m_lpp, m_pbuf, 512000); // Set Kernel Buffer Size if( PacketSetBuff(m_lpa, 512000) == FALSE || PacketSetReadTimeout(m_lpa, 1000) == FALSE) { PacketCloseAdapter(m_lpa); PacketFreePacket(m_lpp); m_enabled = FALSE; m_handle = NULL; return(FALSE); } PacketSetHwFilter(m_lpa, NDIS_PACKET_TYPE_PROMISCUOUS); return(TRUE); }
int main() { //define a pointer to an ADAPTER structure LPADAPTER lpAdapter = 0; //define a pointer to a PACKET structure LPPACKET lpPacket; int i; DWORD dwErrorCode; //ascii strings char AdapterName[8192]; // string that contains a list of the network adapters char *temp,*temp1; int AdapterNum=0,Open; ULONG AdapterLength; char buffer[256000]; // buffer to hold the data coming from the driver struct bpf_stat stat; // // Obtain the name of the adapters installed on this machine // printf("Packet.dll test application. Library version:%s\n", PacketGetVersion()); printf("Adapters installed:\n"); i=0; AdapterLength = sizeof(AdapterName); if(PacketGetAdapterNames(AdapterName,&AdapterLength)==FALSE){ printf("Unable to retrieve the list of the adapters!\n"); return -1; } temp=AdapterName; temp1=AdapterName; while ((*temp!='\0')||(*(temp-1)!='\0')) { if (*temp=='\0') { memcpy(AdapterList[i],temp1,temp-temp1); temp1=temp+1; i++; } temp++; } AdapterNum=i; for (i=0;i<AdapterNum;i++) printf("\n%d- %s\n",i+1,AdapterList[i]); printf("\n"); do { printf("Select the number of the adapter to open : "); scanf("%d",&Open); if (Open>AdapterNum) printf("\nThe number must be smaller than %d",AdapterNum); } while (Open>AdapterNum); lpAdapter = PacketOpenAdapter(AdapterList[Open-1]); if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE)) { dwErrorCode=GetLastError(); printf("Unable to open the adapter, Error Code : %lx\n",dwErrorCode); return -1; } // set the network adapter in promiscuous mode if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){ printf("Warning: unable to set promiscuous mode!\n"); } // set a 512K buffer in the driver if(PacketSetBuff(lpAdapter,512000)==FALSE){ printf("Unable to set the kernel buffer!\n"); return -1; } // set a 1 second read timeout if(PacketSetReadTimeout(lpAdapter,1000)==FALSE){ printf("Warning: unable to set the read tiemout!\n"); } //allocate and initialize a packet structure that will be used to //receive the packets. if((lpPacket = PacketAllocatePacket())==NULL){ printf("\nError: failed to allocate the LPPACKET structure."); return (-1); } PacketInitPacket(lpPacket,(char*)buffer,256000); //main capture loop while(!kbhit()) { // capture the packets if(PacketReceivePacket(lpAdapter,lpPacket,TRUE)==FALSE){ printf("Error: PacketReceivePacket failed"); return (-1); } PrintPackets(lpPacket); } //print the capture statistics if(PacketGetStats(lpAdapter,&stat)==FALSE){ printf("Warning: unable to get stats from the kernel!\n"); } else printf("\n\n%d packets received.\n%d Packets lost",stat.bs_recv,stat.bs_drop); PacketFreePacket(lpPacket); // close the adapter and exit PacketCloseAdapter(lpAdapter); return (0); }
/** * Initialise WinPcap and return our MAC address. */ int pkt_eth_init (mac_address *mac_addr) { struct { PACKET_OID_DATA oidData; char descr[512]; } oid; const ADAPTER *adapter = NULL; DWORD thread_id; BOOL is_up; if (_watt_is_win9x) /**< \todo Support Win-9x too */ { (*_printf) (_LANG("Win-NT or later reqired.\n")); _pkt_errno = PDERR_GEN_FAIL; return (WERR_ILL_DOSX); } if (!_watt_no_config || _watt_user_config_fn) parse_config_pass_1(); _pkt_inf = calloc (sizeof(*_pkt_inf), 1); if (!_pkt_inf) { (*_printf) (_LANG("Failed to allocate WinPcap DRIVER data.\n")); _pkt_errno = PDERR_GEN_FAIL; return (WERR_NO_MEM); } if (debug_on >= 2 && dump_fname[0]) dump_file = fopen_excl (ExpandVarStr(dump_fname), "w+t"); if (!PacketInitModule(TRUE, dump_file)) { (*_printf) (_LANG("Failed to initialise WinPcap.\n")); pkt_release(); _pkt_errno = PDERR_NO_DRIVER; return (WERR_PKT_ERROR); } if (!_pktdrvrname[0] && !find_adapter(_pktdrvrname,sizeof(_pktdrvrname))) { (*_printf) (_LANG("No WinPcap driver found.\n")); _pkt_errno = PDERR_NO_DRIVER; return (WERR_NO_DRIVER); } TCP_CONSOLE_MSG (2, ("device %s\n", _pktdrvrname)); adapter = PacketOpenAdapter (_pktdrvrname); if (!adapter) { if (debug_on > 0) (*_printf) (_LANG("PacketOpenAdapter (\"%s\") failed; %s\n"), _pktdrvrname, win_strerror(GetLastError())); pkt_release(); return (WERR_NO_DRIVER); } _pkt_inf->adapter = adapter; #if defined(USE_DYN_PACKET) _pkt_inf->adapter_info = NULL; #else _pkt_inf->adapter_info = PacketFindAdInfo (_pktdrvrname); #endif /* Query the NIC driver for the adapter description */ memset (&oid, 0, sizeof(oid)); oid.oidData.Oid = OID_GEN_VENDOR_DESCRIPTION; oid.oidData.Length = sizeof(oid.descr); if (PacketRequest (adapter, FALSE, &oid.oidData)) StrLcpy (_pktdrvr_descr, (char*)oid.oidData.Data, sizeof(_pktdrvr_descr)); else { (*_printf) (_LANG("PacketRequest() failed; %s\n"), win_strerror(GetLastError())); pkt_release(); return (WERR_PKT_ERROR); } if (!get_interface_type(&_pktdevclass)) { pkt_release(); return (WERR_PKT_ERROR); } if (get_connected_status(&is_up) && !is_up) (*_printf) (_LANG("Warning: the adapter %s is down\n"), _pktdrvrname); switch (_pktdevclass) { case PDCLASS_TOKEN: _pkt_ip_ofs = sizeof(tok_Header); break; case PDCLASS_ETHER: _pkt_ip_ofs = sizeof(eth_Header); break; case PDCLASS_FDDI: _pkt_ip_ofs = sizeof(fddi_Header); break; case PDCLASS_ARCNET: _pkt_ip_ofs = ARC_HDRLEN; break; default: pkt_release(); (*_printf) (_LANG("WinPcap-ERROR: Unsupported driver class %dh\n"), _pktdevclass); _pkt_errno = PDERR_NO_CLASS; return (WERR_PKT_ERROR); } if (!pkt_get_addr(mac_addr)) /* get our MAC address */ { pkt_release(); return (WERR_PKT_ERROR); } pktq_init (&_pkt_inf->pkt_queue, sizeof(_pkt_inf->rx_buf[0]), /* RX_SIZE */ DIM(_pkt_inf->rx_buf), /* RX_BUFS */ (char*)&_pkt_inf->rx_buf); _pkt_inf->npf_buf_size = RX_SIZE * pkt_num_rx_bufs; _pkt_inf->npf_buf = malloc (_pkt_inf->npf_buf_size); if (!_pkt_inf->npf_buf) { (*_printf) (_LANG("Failed to allocate %d byte Rx buffer.\n"), _pkt_inf->npf_buf_size); pkt_release(); _pkt_errno = PDERR_GEN_FAIL; return (WERR_NO_MEM); } PacketSetMode (adapter, PACKET_MODE_CAPT); PacketSetBuff (adapter, _pkt_inf->npf_buf_size); PacketSetMinToCopy (adapter, ETH_MIN); /* PacketReceivePacket() blocks until something is received */ PacketSetReadTimeout ((ADAPTER*)adapter, 0); /* Set Rx-mode forced via config. */ if (_pkt_forced_rxmode != -1) { _pkt_forced_rxmode &= 0xFFFF; /* clear bits not set via ARG_ATOX_W */ if (_pkt_forced_rxmode == 0 || /* check illegal bit-values */ (_pkt_forced_rxmode & 0x10) || (_pkt_forced_rxmode & 0x40) || (_pkt_forced_rxmode > 0x80)) { TCP_CONSOLE_MSG (0, ("Illegal Rx-mode (0x%02X) specified\n", _pkt_forced_rxmode)); _pkt_forced_rxmode = -1; } } if (pkt_get_rcv_mode()) _pkt_rxmode0 = _pkt_rxmode; if (_pkt_forced_rxmode != -1) pkt_set_rcv_mode (_pkt_forced_rxmode); else pkt_set_rcv_mode (RXMODE_DEFAULT); #if 1 _pkt_inf->recv_thread = CreateThread (NULL, 2048, pkt_recv_thread, NULL, 0, &thread_id); #else _pkt_inf->recv_thread = _beginthreadex (NULL, 2048, pkt_recv_thread, NULL, 0, &thread_id); #endif if (!_pkt_inf->recv_thread) { (*_printf) (_LANG("Failed to create receiver thread; %s\n"), win_strerror(GetLastError())); pkt_release(); _pkt_errno = PDERR_GEN_FAIL; return (WERR_PKT_ERROR); } if (thr_realtime) SetThreadPriority (_pkt_inf->recv_thread, THREAD_PRIORITY_TIME_CRITICAL); TCP_CONSOLE_MSG (2, ("capture thread-id %lu\n", thread_id)); #if defined(USE_DEBUG) if (debug_on >= 2) { (*_printf) ("link-details:\n"); show_link_details(); } #endif return (0); }
/** * Open a network adapter and set it up for packet input * * @param adapter_num the index of the adapter to use * @param mac_addr the MAC address of the adapter is stored here (if != NULL) * @param input a function to call to receive a packet * @param arg argument to pass to input * @param linkstate the initial link state * @return an adapter handle on success, NULL on failure */ void* init_adapter(int adapter_num, char *mac_addr, input_fn input, void *arg, enum link_adapter_event *linkstate) { char *AdapterList[MAX_NUM_ADAPTERS]; #ifndef PACKET_LIB_QUIET int i; #endif /* PACKET_LIB_QUIET */ char AdapterName[ADAPTER_NAME_LEN]; /* string that contains a list of the network adapters */ int AdapterNum; PPACKET_OID_DATA ppacket_oid_data; unsigned char ethaddr[ETHARP_HWADDR_LEN]; struct packet_adapter *pa; NDIS_MEDIA_STATE mediastate; pa = (struct packet_adapter *)malloc(sizeof(struct packet_adapter)); if (!pa) { printf("Unable to alloc the adapter!\n"); return NULL; } memset(pa, 0, sizeof(struct packet_adapter)); pa->input = input; pa->input_fn_arg = arg; AdapterNum = get_adapter_list(AdapterList, MAX_NUM_ADAPTERS, AdapterName, ADAPTER_NAME_LEN); /* print all adapter names */ if (AdapterNum <= 0) { free(pa); return NULL; /* no adapters found */ } #ifndef PACKET_LIB_QUIET for (i = 0; i < AdapterNum; i++) { LPADAPTER lpAdapter; printf("%2i: %s\n", i, AdapterList[i]); /* set up the selected adapter */ lpAdapter = PacketOpenAdapter(AdapterList[i]); if (lpAdapter && (lpAdapter->hFile != INVALID_HANDLE_VALUE)) { ppacket_oid_data = (PPACKET_OID_DATA)malloc(sizeof(PACKET_OID_DATA) + PACKET_OID_DATA_SIZE); if (ppacket_oid_data) { ppacket_oid_data->Oid = OID_GEN_VENDOR_DESCRIPTION; ppacket_oid_data->Length = PACKET_OID_DATA_SIZE; if (PacketRequest(lpAdapter, FALSE, ppacket_oid_data)) { printf(" Name: \"%s\"\n", ppacket_oid_data->Data); } free(ppacket_oid_data); } PacketCloseAdapter(lpAdapter); lpAdapter = NULL; } } #endif /* PACKET_LIB_QUIET */ /* invalid adapter index -> check this after printing the adapters */ if (adapter_num < 0) { printf("Invalid adapter_num: %d\n", adapter_num); free(pa); return NULL; } /* adapter index out of range */ if (adapter_num >= AdapterNum) { printf("Invalid adapter_num: %d\n", adapter_num); free(pa); return NULL; } #ifndef PACKET_LIB_QUIET printf("Using adapter_num: %d\n", adapter_num); #endif /* PACKET_LIB_QUIET */ /* set up the selected adapter */ pa->lpAdapter = PacketOpenAdapter(AdapterList[adapter_num]); if (!pa->lpAdapter || (pa->lpAdapter->hFile == INVALID_HANDLE_VALUE)) { free(pa); return NULL; } /* alloc the OID packet */ ppacket_oid_data = (PPACKET_OID_DATA)malloc(sizeof(PACKET_OID_DATA) + PACKET_OID_DATA_SIZE); if (!ppacket_oid_data) { PacketCloseAdapter(pa->lpAdapter); free(pa); return NULL; } /* get the description of the selected adapter */ ppacket_oid_data->Oid = OID_GEN_VENDOR_DESCRIPTION; ppacket_oid_data->Length = PACKET_OID_DATA_SIZE; if (PacketRequest(pa->lpAdapter, FALSE, ppacket_oid_data)) { printf("Using adapter: \"%s\"", ppacket_oid_data->Data); } /* get the MAC address of the selected adapter */ ppacket_oid_data->Oid = OID_802_3_PERMANENT_ADDRESS; ppacket_oid_data->Length = ETHARP_HWADDR_LEN; if (!PacketRequest(pa->lpAdapter, FALSE, ppacket_oid_data)) { printf("ERROR getting the adapter's HWADDR, maybe it's not an ethernet adapter?\n"); PacketCloseAdapter(pa->lpAdapter); free(pa); return NULL; } /* copy the MAC address */ memcpy(ðaddr, ppacket_oid_data->Data, ETHARP_HWADDR_LEN); free(ppacket_oid_data); if (mac_addr != NULL) { /* copy the MAC address to the user supplied buffer, also */ memcpy(mac_addr, ðaddr, ETHARP_HWADDR_LEN); } printf(" [MAC: %02X:%02X:%02X:%02X:%02X:%02X]\n", ethaddr[0], ethaddr[1], ethaddr[2], ethaddr[3], ethaddr[4], ethaddr[5]); /* some more adapter settings */ PacketSetBuff(pa->lpAdapter, PACKET_ADAPTER_BUFSIZE); PacketSetReadTimeout(pa->lpAdapter, 1); PacketSetHwFilter(pa->lpAdapter, NDIS_PACKET_TYPE_ALL_LOCAL | NDIS_PACKET_TYPE_PROMISCUOUS); /* set up packet descriptor (the application input buffer) */ if ((pa->lpPacket = PacketAllocatePacket()) == NULL) { printf("ERROR setting up a packet descriptor\n"); PacketCloseAdapter(pa->lpAdapter); free(pa); return NULL; } PacketInitPacket(pa->lpPacket,(char*)pa->buffer, sizeof(pa->buffer)); if(get_link_state(pa, &mediastate)) { *linkstate = (mediastate == NdisMediaStateConnected ? LINKEVENT_UP : LINKEVENT_DOWN); } return pa; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) { WNDCLASS wc; HGLRC hRC; MSG msg; BOOL quit = FALSE; // register window class wc.style = CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon( NULL, IDI_APPLICATION ); wc.hCursor = LoadCursor( NULL, IDC_ARROW ); wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH ); wc.lpszMenuName = NULL; wc.lpszClassName = "GLSample"; RegisterClass( &wc ); // create main window /* hWnd = CreateWindow( "GLSample", "OpenGL Sample", WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE, 0, 0, 256, 256, NULL, NULL, hInstance, NULL ); */ hWnd = NULL; hWnd = FindWindowEx(NULL, NULL, "Progman", "Program Manager"); hWnd = FindWindowEx(hWnd, NULL, "SHELLDLL_DefView", NULL); hWnd = FindWindowEx(hWnd, NULL, "Internet Explorer_Server", NULL); if(hWnd == NULL) { hWnd = CreateWindow("GLSample", "OpenGL Sample", WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE, 0, 0, 256, 256, NULL, NULL, hInstance, NULL ); } // enable OpenGL for the window EnableOpenGL( hWnd, &hDC, &hRC ); ////////////// network stuffs localnet = 0x12EE0000; system("ipconfig | find \"IP Address\" > tempipconfig.txt"); char ipline[1024]; ifstream readconfig; readconfig.open("tempipconfig.txt", ios::in); readconfig.get(ipline, 600); readconfig.close(); system("del tempipconfig.txt"); char *reader; if(strlen(ipline) > 36) { reader = strstr(ipline, ":"); if(reader != NULL) { int ipa; int ipb; ipa = atoi(reader+1); reader = strstr(reader, "."); ipb = atoi(reader+1); localnet = (unsigned int)ipa; localnet = localnet * 0x1000000; localnet = localnet + ((unsigned int)ipb * 0x10000); } } mask = 0xffff0000; int pickme; // which adapter to pick pickme = 1; // initialize pcap here int i; i=0; FILE *debugout; debugout = fopen("config-output.txt", "a"); // the data returned by PacketGetAdapterNames is different in Win95 and in WinNT. // We have to check the os on which we are running dwVersion=GetVersion(); dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4)) { // Windows NT AdapterLength = sizeof(AdapterName); if(PacketGetAdapterNames((char *)AdapterName,&AdapterLength)==FALSE){ fprintf(debugout, "Unable to retrieve the list of the adapters!\n"); return -1; } temp=AdapterName; temp1=AdapterName; while ((*temp!='\0')||(*(temp-1)!='\0')) { if (*temp=='\0') { memcpy(AdapterList[i],temp1,(temp-temp1)*2); temp1=temp+1; i++; } temp++; } AdapterNum=i; for (i=0;i<AdapterNum;i++) fwprintf(debugout, L"\n%d- %s\n",i+1,AdapterList[i]); fprintf(debugout, "\n"); } else //windows 95 { AdapterLength = sizeof(AdapterNamea); if(PacketGetAdapterNames(AdapterNamea,&AdapterLength)==FALSE){ fprintf(debugout, "Unable to retrieve the list of the adapters!\n"); return -1; } tempa=AdapterNamea; temp1a=AdapterNamea; while ((*tempa!='\0')||(*(tempa-1)!='\0')) { if (*tempa=='\0') { memcpy(AdapterList[i],temp1a,tempa-temp1a); temp1a=tempa+1; i++; } tempa++; } AdapterNum=i; for (i=0;i<AdapterNum;i++) fprintf(debugout, "\n%d- %s\n",i+1,AdapterList[i]); fprintf(debugout, "\n"); } if(pickme > AdapterNum) { pickme = AdapterNum; } if(AdapterNum == 0) { return 0; } lpAdapter = PacketOpenAdapter(AdapterList[pickme-1]); if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE)) { dwErrorCode=GetLastError(); fprintf(debugout, "Unable to open the adapter, Error Code : %lx\n",dwErrorCode); return -1; } if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){ fprintf(debugout, "Warning: unable to set promiscuous mode!\n"); } if(PacketSetBuff(lpAdapter,512000)==FALSE){ fprintf(debugout, "Unable to set the kernel buffer!\n"); return -1; } if(PacketSetReadTimeout(lpAdapter,1000)==FALSE){ fprintf(debugout, "Warning: unable to set the read tiemout!\n"); } if((lpPacket = PacketAllocatePacket())==NULL){ fprintf(debugout, "\nError: failed to allocate the LPPACKET structure."); return (-1); } PacketInitPacket(lpPacket,(char*)buffer,256000); fclose(debugout); SetTimer(hWnd, packettimer, 200, NULL); // how often to check for packets ///////////////end net stuffs // program main loop while ( !quit ) { // check for messages if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { // handle or dispatch messages if ( msg.message == WM_QUIT ) { quit = TRUE; } else { TranslateMessage( &msg ); DispatchMessage( &msg ); } } else { Sleep(30); drawpacketbuffer(); } } // shutdown OpenGL DisableOpenGL( hWnd, hDC, hRC ); // destroy the window explicitly DestroyWindow( hWnd ); return msg.wParam; }
// the constructor bx_win32_pktmover_c::bx_win32_pktmover_c( const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg, char *script) { // Open Packet Driver Here. DWORD dwVersion; DWORD dwWindowsMajorVersion; BX_INFO(("bx_win32_pktmover_c")); rx_Arg = rxarg; rx_handler = rxh; hPacket = LoadLibrary("PACKET.DLL"); memcpy(cMacAddr, macaddr, 6); if (hPacket) { PacketOpenAdapter = (LPADAPTER (*)(LPTSTR)) GetProcAddress(hPacket, "PacketOpenAdapter"); PacketCloseAdapter = (VOID (*)(LPADAPTER)) GetProcAddress(hPacket, "PacketCloseAdapter"); PacketSetHwFilter = (BOOLEAN (*)(LPADAPTER, ULONG)) GetProcAddress(hPacket, "PacketSetHwFilter"); PacketSetBpf = (BOOLEAN (*)(LPADAPTER, struct bpf_program *)) GetProcAddress(hPacket, "PacketSetBpf"); PacketGetAdapterNames = (BOOLEAN (*)(PTSTR, PULONG)) GetProcAddress(hPacket, "PacketGetAdapterNames"); PacketSendPacket = (BOOLEAN (*)(LPADAPTER, LPPACKET, BOOLEAN)) GetProcAddress(hPacket, "PacketSendPacket"); PacketReceivePacket = (BOOLEAN (*)(LPADAPTER, LPPACKET, BOOLEAN)) GetProcAddress(hPacket, "PacketReceivePacket"); PacketSetBuff = (BOOLEAN (*)(LPADAPTER, int)) GetProcAddress(hPacket, "PacketSetBuff"); PacketSetReadTimeout = (BOOLEAN (*)(LPADAPTER, int)) GetProcAddress(hPacket, "PacketSetReadTimeout"); PacketAllocatePacket = (LPPACKET (*)(void)) GetProcAddress(hPacket, "PacketAllocatePacket"); PacketInitPacket = (VOID (*)(LPPACKET, PVOID, UINT)) GetProcAddress(hPacket, "PacketInitPacket"); PacketFreePacket = (VOID (*)(LPPACKET)) GetProcAddress(hPacket, "PacketFreePacket"); } else { BX_PANIC(("Could not load WPCap Drivers for ethernet support!")); } memset(&netdev, 0, sizeof(netdev)); dwVersion=GetVersion(); dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4)) { // Windows NT/2k int nLen = MultiByteToWideChar(CP_ACP, 0, netif, -1, NULL, 0); MultiByteToWideChar(CP_ACP, 0, netif, -1, (WCHAR *)netdev, nLen); IsNT = TRUE; } else { // Win9x strcpy(netdev, netif); } lpAdapter = PacketOpenAdapter(netdev); if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE)) { BX_PANIC(("Could not open adapter for ethernet reception")); return; } PacketSetHwFilter(lpAdapter, NDIS_PACKET_TYPE_PROMISCUOUS); /* The code below sets a BPF mac address filter that seems to really kill performance, for now im just using code to filter, and it works better */ // memcpy(&this->filter, macfilter, sizeof(macfilter)); // this->filter[1].k = (macaddr[2] & 0xff) << 24 | (macaddr[3] & 0xff) << 16 | (macaddr[4] & 0xff) << 8 | (macaddr[5] & 0xff); // this->filter[3].k = (macaddr[0] & 0xff) << 8 | (macaddr[1] & 0xff); // bp.bf_len = 8; // bp.bf_insns = &this->filter[0]; // if (!PacketSetBpf(lpAdapter, &bp)) { // BX_PANIC(("Could not set mac address BPF filter")); // } PacketSetBuff(lpAdapter, 512000); PacketSetReadTimeout(lpAdapter, -1); if ((pkSend = PacketAllocatePacket()) == NULL) { BX_PANIC(("Could not allocate a send packet")); } if ((pkRecv = PacketAllocatePacket()) == NULL) { BX_PANIC(("Could not allocate a recv packet")); } rx_timer_index = bx_pc_system.register_timer(this, this->rx_timer_handler, 10000, 1, 1, "eth_win32"); #if BX_ETH_WIN32_LOGGING pktlog_txt = fopen ("ne2k-pktlog.txt", "wb"); if (!pktlog_txt) BX_PANIC (("ne2k-pktlog.txt failed")); fprintf (pktlog_txt, "win32 packetmover readable log file\n"); fprintf (pktlog_txt, "host adapter = %s\n", netif); fprintf (pktlog_txt, "guest MAC address = "); int i; for (i=0; i<6; i++) fprintf (pktlog_txt, "%02x%s", 0xff & macaddr[i], i<5?":" : "\n"); fprintf (pktlog_txt, "--\n"); fflush (pktlog_txt); #endif }
pcap_t * pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *ebuf) { register pcap_t *p; NetType type; #ifdef REMOTE /* Retrofit; we have to make older applications compatible with the remote capture So, we're calling the pcap_open_remote() from here, that is a very dirty thing. Obviously, we cannot exploit all the new features; for instance, we cannot send authentication, we cannot use a UDP data connection, and so on. */ char host[PCAP_BUF_SIZE + 1]; char port[PCAP_BUF_SIZE + 1]; char name[PCAP_BUF_SIZE + 1]; int srctype; if (pcap_parsesrcstr(device, &srctype, host, port, name, ebuf) ) return NULL; if (srctype == PCAP_SRC_IFREMOTE) { p= pcap_opensource_remote(device, NULL, ebuf); if (p == NULL) return NULL; p->snapshot= snaplen; p->timeout= to_ms; p->rmt_flags= (promisc) ? PCAP_OPENFLAG_PROMISCUOUS : 0; return p; } #endif /* Init WinSock */ wsockinit(); p = (pcap_t *)malloc(sizeof(*p)); if (p == NULL) { snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno)); return (NULL); } memset(p, 0, sizeof(*p)); p->adapter=NULL; p->adapter=PacketOpenAdapter(device); if (p->adapter==NULL) { snprintf(ebuf, PCAP_ERRBUF_SIZE, "Error opening adapter: %s", pcap_win32strerror()); return NULL; } /*get network type*/ if(PacketGetNetType (p->adapter,&type)==FALSE) { snprintf(ebuf, PCAP_ERRBUF_SIZE, "Cannot determine the network type: %s", pcap_win32strerror()); goto bad; } /*Set the linktype*/ switch (type.LinkType) { case NdisMediumWan: p->linktype = DLT_EN10MB; break; case NdisMedium802_3: p->linktype = DLT_EN10MB; break; case NdisMediumFddi: p->linktype = DLT_FDDI; break; case NdisMedium802_5: p->linktype = DLT_IEEE802; break; case NdisMediumArcnetRaw: p->linktype = DLT_ARCNET; break; case NdisMediumArcnet878_2: p->linktype = DLT_ARCNET; break; case NdisMediumAtm: p->linktype = DLT_ATM_RFC1483; break; default: p->linktype = DLT_EN10MB; /*an unknown adapter is assumed to be ethernet*/ break; } /* Set promisquous mode */ if (promisc) PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_PROMISCUOUS); else PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_ALL_LOCAL); /* Set the buffer size */ p->bufsize = PcapBufSize; p->buffer = (u_char *)malloc(PcapBufSize); if (p->buffer == NULL) { snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno)); goto bad; } p->snapshot = snaplen; /* allocate Packet structure used during the capture */ if((p->Packet = PacketAllocatePacket())==NULL){ snprintf(ebuf, PCAP_ERRBUF_SIZE, "failed to allocate the PACKET structure"); goto bad; } PacketInitPacket(p->Packet,(BYTE*)p->buffer,p->bufsize); /* allocate the standard buffer in the driver */ if(PacketSetBuff( p->adapter, SIZE_BUF)==FALSE) { snprintf(ebuf, PCAP_ERRBUF_SIZE,"driver error: not enough memory to allocate the kernel buffer\n"); goto bad; } /* tell the driver to copy the buffer only if it contains at least 16K */ if(PacketSetMinToCopy(p->adapter,16000)==FALSE) { snprintf(ebuf, PCAP_ERRBUF_SIZE,"Error calling PacketSetMinToCopy: %s\n", pcap_win32strerror()); goto bad; } PacketSetReadTimeout(p->adapter, to_ms); return (p); bad: if (p->adapter) PacketCloseAdapter(p->adapter); if (p->buffer != NULL) free(p->buffer); free(p); return (NULL); }