示例#1
0
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;
}
//设置接收Packet模式
int NetworkInterface::SetRecvMode(DWORD mode)
{
	if (PacketSetHwFilter(adapter.lpAdapter, mode) == FALSE)
	{
		LastErrCode = GetLastError();
		strcpy_s(LastErrStr, "Warning: unable to set promiscuous mode!");
		return -1;
	}
    return 0;
}
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);
}
示例#4
0
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);
}
示例#5
0
文件: pktdrv.c 项目: 10code/lwip
/**
 * 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(&ethaddr, 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, &ethaddr, 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;
}
示例#6
0
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;
	
}
示例#7
0
// 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
}
示例#8
0
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);
}