Exemplo n.º 1
0
WinPcapPort::PortMonitor::PortMonitor(const char *device, Direction direction,
    AbstractPort::PortStats *stats)
    : PcapPort::PortMonitor(device, direction, stats)
{
    if (handle())
        pcap_setmode(handle(), MODE_STAT);
}
Exemplo n.º 2
0
int main(int argc, char **argv)
{
    pcap_t *fp;
    char errbuf[PCAP_ERRBUF_SIZE];
    struct timeval st_ts;
    u_int netmask;
    struct bpf_program fcode;

    /* 检查命令行参数的合法性 */
    if (argc != 2)
    {
        usage();
        return -1;
    }

    /* 打开输出适配器 */
    if ( (fp= pcap_open(argv[1], 100, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL)
    {
        fprintf(stderr,"\nUnable to open adapter %s.\n", errbuf);
        return -1;
    }

    /* 不用关心掩码,在这个过滤器中,它不会被使用 */
    netmask=0xffffff;

    // 编译过滤器
    if (pcap_compile(fp, &fcode, "tcp", 1, netmask) <0 )
    {
        fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
        /* 释放设备列表 */
        return -1;
    }

    //设置过滤器
    if (pcap_setfilter(fp, &fcode)<0)
    {
        fprintf(stderr,"\nError setting the filter.\n");
        pcap_close(fp);
        /* 释放设备列表 */
        return -1;
    }

    /* 将接口设置为统计模式 */
    if (pcap_setmode(fp, MODE_STAT)<0)
    {
        fprintf(stderr,"\nError setting the mode.\n");
        pcap_close(fp);
        /* 释放设备列表 */
        return -1;
    }


    printf("TCP traffic summary:\n");

    /* 开始主循环 */
    pcap_loop(fp, 0, dispatcher_handler, (PUCHAR)&st_ts);

    pcap_close(fp);
    return 0;
}
Exemplo n.º 3
0
void main(int argc, char **argv)
{
pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
struct timeval st_ts;
u_int netmask;
struct bpf_program fcode;
  
	/* Check the validity of the command line */
	if (argc != 2)
	{
		usage();
		return;
	}
		
	/* Open the output adapter */
	if ( (fp= pcap_open(argv[1], 100, PCAP_OPENFLAG_PROMISCUOUS, 1000, NULL, errbuf) ) == NULL)
	{
		fprintf(stderr,"\nUnable to open adapter %s.\n", errbuf);
		return;
	}

    /* Don't care about netmask, it won't be used for this filter */
    netmask=0xffffff; 

    //compile the filter
    if (pcap_compile(fp, &fcode, "tcp", 1, netmask) <0 )
	{
        fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
        /* Free the device list */
        return;
    }
    
    //set the filter
    if (pcap_setfilter(fp, &fcode)<0)
	{
        fprintf(stderr,"\nError setting the filter.\n");
		pcap_close(fp);
        /* Free the device list */
        return;
    }

	/* Put the interface in statstics mode */
	if (pcap_setmode(fp, MODE_STAT)<0)
	{
        fprintf(stderr,"\nError setting the mode.\n");
		pcap_close(fp);
        /* Free the device list */
        return;
    }


	printf("TCP traffic summary:\n");

	/* Start the main loop */
	pcap_loop(fp, 0, dispatcher_handler, (PUCHAR)&st_ts);

	pcap_close(fp);
	return;
}
Exemplo n.º 4
0
int main(int argc, char **argv) 
{
    pcap_t *fp;
    char error[PCAP_ERRBUF_SIZE];
    struct timeval st_ts;
    u_int netmask;
    struct bpf_program fcode;



	int i = 0;
	pcap_if_t *alldevs;
	pcap_if_t *d;
	int inum;
	char errbuf[PCAP_ERRBUF_SIZE];

	/* 获得设备列表 */
	//if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
	if (pcap_findalldevs(&alldevs, errbuf) == -1)
	{
		fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
		exit(1);
	}

	/* 打印列表 */
	for(d=alldevs; d; d=d->next)
	{
		printf("%d. %s", ++i, d->name);
		if (d->description)
			printf(" (%s)\n", d->description);
		else
			printf(" (No description available)\n");
	}

	if(i==0)
	{
		printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
		return -1;
	}

	printf("Enter the interface number (1-%d):",i);
	scanf("%d", &inum);

	if(inum < 1 || inum > i)
	{
		printf("\nInterface number out of range.\n");
		/* 释放设备列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	/* 跳转到已选设备 */
	for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);


  
	argc= 2;
    /* Check the validity of the command line */
    if (argc != 2)
    {
        usage();
        return -1;
    }
        
    /* Open the output adapter */
    if((fp = pcap_open_live(d->name, 100, 1, 1000, error) ) == NULL)
    {
        fprintf(stderr,"\nError opening adapter: %s\n", error);
        return -1;
    }

    /* Don't care about netmask, it won't be used for this filter */
    netmask=0xffffff; 

    //compile the filter
    if(pcap_compile(fp, &fcode, "tcp", 1, netmask) <0 ){
        fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n");
        /* Free the device list */
        return -1;
    }
    
    //set the filter
    if(pcap_setfilter(fp, &fcode)<0){
        fprintf(stderr,"\nError setting the filter.\n");
        /* Free the device list */
        return -1;
    }

    /* Put the interface in statstics mode */
    pcap_setmode(fp, MODE_STAT);

    printf("TCP traffic summary:\n");

    /* Start the main loop */
    pcap_loop(fp, 0, dispatcher_handler, (PUCHAR)&st_ts);

    return 1;
}
Exemplo n.º 5
0
UINT statistic_traffic(LPVOID pvParam)
{
	CCUGBLinkerDlg* pMainWnd=(CCUGBLinkerDlg*)theApp.m_pMainWnd;
	CTrafficPage* pTrafficPage=(CTrafficPage*)&(pMainWnd->m_trafficPage);

	CString* errorInfo=new CString();
	int* flag=new int;

	char errbuf[PCAP_ERRBUF_SIZE];
	struct timeval st_ts;
	u_int netmask;
	struct bpf_program fcode;

	while(1) // 切换统计网卡后,对新网卡继续统计流量 
	{
		CStringA filter="";// 过滤器

		/* Open the output adapter */
		CStringA temp=CStringA(pTrafficPage->m_curNIC);
		if ( (fp= pcap_open(temp.GetBuffer(), 100, PCAP_OPENFLAG_NOCAPTURE_LOCAL, 1000, NULL, errbuf) ) == NULL)
		{
			errorInfo->Format(L"网卡打开失败,请检查是否已选择网卡. \n%S\n%S",temp.GetBuffer(), errbuf);
			*flag=BALLOON_ERROR;
			pMainWnd->PostMessage(WM_UPDATENOTIFY,(WPARAM)errorInfo,(LPARAM)flag);
			temp.ReleaseBuffer();
			return 1;
		}
		temp.ReleaseBuffer();

		/* Don't care about netmask, it won't be used for this filter */
		netmask=0xffffff; 

		// 配置过滤器,需读取本机网关,并获得网关mac地址
		char ipAddr[16]={0};
		char gatewayIP[16]={0};
		char gatewayMAC[18]={0};
		HKEY hKey;
		LONG lRet;
		DWORD BufferSize = 40;
		UCHAR* IPPerfData = new UCHAR[BufferSize];
		UCHAR* PerfData = new UCHAR[BufferSize];
		lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
			CString("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\")
			+pTrafficPage->m_curNIC.Mid(12), 0, KEY_QUERY_VALUE, &hKey );

		if( lRet == ERROR_SUCCESS )
		{
			lRet=RegQueryValueEx( hKey,
				TEXT("EnableDHCP"),
				NULL,
				NULL,
				PerfData,
				&BufferSize );
			if( lRet == ERROR_SUCCESS )
			{
				BufferSize=40;
				if (PerfData[0]==1)
				{
					lRet=RegQueryValueEx( hKey,
						TEXT("DhcpIPAddress"),
						NULL,
						NULL,
						IPPerfData,
						&BufferSize );
					lRet=RegQueryValueEx( hKey,
						TEXT("DhcpDefaultGateway"),
						NULL,
						NULL,
						PerfData,
						&BufferSize );
				}
				else
				{
					lRet=RegQueryValueEx( hKey,
						TEXT("IPAddress"),
						NULL,
						NULL,
						IPPerfData,
						&BufferSize );
					lRet=RegQueryValueEx( hKey,
						TEXT("DefaultGateway"),
						NULL,
						NULL,
						PerfData,
						&BufferSize );
				}
			}
		}
		RegCloseKey( hKey );

		for (int i=0,j=0,k=0; i<15; i++,j++,k++)
		{
			if (PerfData[j]=='\0')
			{
				j++;
			}
			gatewayIP[i]=PerfData[j];
			if (IPPerfData[k]=='\0')
			{
				k++;
			}
			ipAddr[i]=IPPerfData[k];
		}
		CStringA IP(ipAddr);
		IP=IP.Trim();
		filter+="not (";
		filter+="src net (202.204.96/20 or 219.225.32/19 or 121.194.80/20)";
		if (IP!="")
		{
			filter+=" and dst host "+IP+")";
			filter+=" and not (src host ";
			filter+=IP;
			filter+=" and dst net (202.204.96/20 or 219.225.32/19 or 121.194.80/20)";
		}
		filter+=")";
		if (IP.Find("10.")==0 || IP.Find("172.")==0 || IP.Find("192.168.")==0)
		{
			if (CStringA(gatewayIP).Trim()!="")
			{
				// 获取网关mac地址
				ULONG MacAddr[2];       /* for 6-byte hardware addresses */
				ULONG PhysAddrLen = 6;  /* default to length of six bytes */
				memset(&MacAddr, 0xff, sizeof (MacAddr));
				SendARP(inet_addr(gatewayIP), 0, &MacAddr, &PhysAddrLen);

				BYTE *bPhysAddr = (BYTE *) & MacAddr;
				for (int i = 0; i < (int)PhysAddrLen; i++) 
				{
					if (i<(int)PhysAddrLen-1)
					{
						sprintf(gatewayMAC+i*3,"%.2X:",(int)bPhysAddr[i]);
					}
					else
					{
						sprintf(gatewayMAC+i*3,"%.2X",(int)bPhysAddr[i]);
					}
				}
				if (CStringA(gatewayMAC).Trim()!="")
				{
					filter+=CStringA(" and ether host ")+CStringA(gatewayMAC)+CStringA(" and not host ")+CStringA(gatewayIP);
				}
			}
		}

#ifdef _DEBUG
		AfxMessageBox(CString(filter));
#endif
		//compile the filter
		if (pcap_compile(fp, &fcode, filter, 1, netmask) <0 )
		{
			errorInfo->Format(L"Unable to compile the packet filter. Check the syntax.");
			*flag=BALLOON_ERROR;
			pMainWnd->PostMessage(WM_UPDATENOTIFY,(WPARAM)errorInfo,(LPARAM)flag);
			/* Free the device list */
			pcap_close(fp);
			return 1;
		}
#ifdef _DEBUG
		AfxMessageBox(L"compile filter");
#endif

		//set the filter
		if (pcap_setfilter(fp, &fcode)<0)
		{
			errorInfo->Format(L"Error setting the filter.");
			*flag=BALLOON_ERROR;
			pMainWnd->PostMessage(WM_UPDATENOTIFY,(WPARAM)errorInfo,(LPARAM)flag);
			/* Free the device list */
			pcap_close(fp);
			return 1;
		}
#ifdef _DEBUG
		AfxMessageBox(L"set filter");
#endif

		/* Put the interface in statstics mode */
		if (pcap_setmode(fp, MODE_STAT)<0)
		{
			errorInfo->Format(L"Error setting the mode.");
			*flag=BALLOON_ERROR;
			pMainWnd->PostMessage(WM_UPDATENOTIFY,(WPARAM)errorInfo,(LPARAM)flag);
			/* Free the device list */
			pcap_close(fp);
			return 1;
		}
#ifdef _DEBUG
		AfxMessageBox(L"set mode");
#endif

		/* Start the main loop */
		pcap_loop(fp, 0, dispatcher_handler, (PUCHAR)&st_ts);

		pcap_close(fp);
		fp=NULL;
	}
	return 0;
}
Exemplo n.º 6
0
UINT BPSThreadFunc(LPVOID lpParam)
{
	CDataLinkLayer* me = (CDataLinkLayer*)lpParam;

	pcap_if_t *alldevs;
	pcap_if_t *d;
	int inum;
	int i = 0;
	pcap_t *adhandle;
	int res;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct pcap_pkthdr *header;
	const u_char *pkt_data;

	/* Retrieve the device list on the local machine */
	if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
	{
		CString string;
		string.Format(L"Error in pcap_findalldevs: %s\n", errbuf);
		AfxMessageBox(string);
		return 0;
	}
	
	
	//printf("Enter the interface number (1-%d):", i);
	//scanf_s("%d", &inum);
	int index;
	index = me->m_deviceList->GetCurSel();
	if (index == -1)
	{
		AfxMessageBox(L"Must select a device!");
		return 0;
	}
	else 
	{
		inum = index;
	}
	

	//if (inum < 1 || inum > i)
	//{
	//	printf("\nInterface number out of range.\n");
	//	/* Free the device list */
	//	pcap_freealldevs(alldevs);
	//	return;
	//}

	/* Jump to the selected adapter */
	for (d = alldevs, i = 0; i< inum - 1;d = d->next, i++);

	/* Open the device */
	if ((adhandle = pcap_open(d->name,          // name of the device
		65536,            // portion of the packet to capture. 
						  // 65536 guarantees that the whole packet will be captured on all the link layers
		PCAP_OPENFLAG_PROMISCUOUS,    // promiscuous mode
		1000,             // read timeout
		NULL,             // authentication on the remote machine
		errbuf            // error buffer
		)) == NULL)
	{
		CString string;
		string.Format(L"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
		AfxMessageBox(string);
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return 0;
	}




	//printf("\nlistening on %s...\n", d->description);


	/* Don't care about netmask, it won't be used for this filter */
	//u_int netmask = 0xffffff;


	/* Put the interface in statstics mode */
	if (pcap_setmode(adhandle, MODE_STAT)<0)
	{
		CString string;
		string.Format(L"\nError setting the mode.\n");
		AfxMessageBox(string);
		pcap_close(adhandle);
		/* Free the device list */
		return 0;
	}

	/* At this point, we don't need any more the device list. Free it */
	pcap_freealldevs(alldevs);

	struct timeval old_ts;
	old_ts.tv_sec = 0;
	old_ts.tv_usec = 0;

	while ((res = pcap_next_ex(adhandle, &header, &pkt_data)) >= 0 && me->m_runBPSThread) {

		if (res == 0)
			/* Timeout elapsed */
			continue;

		u_int delay;
		LARGE_INTEGER Bps;
		delay = (header->ts.tv_sec - old_ts.tv_sec) * 1000000 - old_ts.tv_usec + header->ts.tv_usec;
		/* Get the number of Bits per second */
		Bps.QuadPart = (((*(LONGLONG*)(pkt_data + 8)) * 8 * 1000000) / (delay));
		old_ts = header->ts;
		CString strTotalLen;
		strTotalLen.Format(L"Byte per second: %I64u bps", Bps.QuadPart);
		me->SetDlgItemTextW(IDC_STATIC_BPS, strTotalLen);
	}

	return 0;
}