Ejemplo n.º 1
0
int KSGNetUtil::GetMacByIP(const std::string ip, std::string &mac)
{
	char mac_str[30] = "";
	int nRemoteAddr = inet_addr( ip.c_str() );
	hostent host;
	hostent * remoteHostent= &host;
	struct in_addr sa;
	memset(&host,0,sizeof(host));
	//获取远程机器名
	sa.s_addr = nRemoteAddr;
	remoteHostent = gethostbyaddr( (char*)&nRemoteAddr,4, AF_INET );
	if ( NULL == remoteHostent )
		return -1;
	//发送ARP查询包获得远程MAC地址

	unsigned char macAddress[6];
	ULONG macAddLen = 6;
	DWORD iRet=SendARP(nRemoteAddr, (unsigned long)NULL,(PULONG)&macAddress, &macAddLen);
	if ( NO_ERROR == iRet )
	{
		int i =0;
		int j = 0;
		for( ; i<5; i++ )
		{
			j += sprintf(mac_str+j,"%.2X-", macAddress[i] );
		}
		sprintf(mac_str+j,"%.2X",macAddress[i]);
		mac = mac_str;
	}
	else
		return -1;
	return 0;
}
Ejemplo n.º 2
0
bool SocketGetMacByIP(char *szIP, char *szMac)
{
	/*MIB_IPNETTABLE  IpNetTable;
	MIB_IPNETTABLE  *pIpNetTable = (MIB_IPNETTABLE *)malloc(246);
	DWORD   status   =   NO_ERROR;   
	//DWORD   statusRetry   =   NO_ERROR;   
	DWORD   dwActualSize   =   0;   
	          DWORD   i,   dwStatus,   dwCurrIndex;   
          struct   in_addr   inadTmp;   
          char   szPrintablePhysAddr[256];   
          char   szType[128];   
          char   szIpAddr[128];   
          PMIB_IPADDRTABLE   pIpAddrTable   =   NULL;   

	//   query   for   buffer   size   needed   
	dwActualSize   =   0;   
	status   =   GetIpNetTable(&IpNetTable,   &dwActualSize,  true);  
	if (status   ==   ERROR_INSUFFICIENT_BUFFER)   
	{   
		pIpNetTable   =   (PMIB_IPNETTABLE)   malloc(dwActualSize);   

		status   =   GetIpNetTable(pIpNetTable,   &dwActualSize,   true);   

		if   (status   !=   NO_ERROR)   
		{   
			return false; 
		}   
	}   
	if (status == NO_ERROR)
	{
		for   (i   =   0;   i   <   pIpNetTable->dwNumEntries;   ++i)   
          {    
          PhysAddrToString(pIpNetTable->table[i].bPhysAddr,   pIpNetTable->table[i].dwPhysAddrLen,   szPrintablePhysAddr);   
		  printf("mac :%s\n" , szPrintablePhysAddr);
		  }
	}
	return false;*/
	
	unsigned   char   macAddress[6]; 
	int i;
                  ULONG   macAddLen   =   6;   
                int  iRet=SendARP(inet_addr(szIP),   (unsigned   long)NULL,(PULONG)&macAddress,   &macAddLen); 
				if   (  iRet   ==   NO_ERROR   )   
                  {   
                          printf(   "MacAddress:   "   );   
                          for(     i   =0;   i<6;   i++   )   
                          {   
                                  printf(   "%.2x",   macAddress[i]   );   
                                  if   (   i<5   )   printf(   "-"   );   
                          }   
                          printf(   "\n"   );   
                  }   
else   
                          printf(   "SendARP   Error:%d\n",   GetLastError());   
                          //nRemoteAddr   =   htonl(   ntohl(   nRemoteAddr   )   +   1   );   

				return true;

}
Ejemplo n.º 3
0
/******************
 * get the destination address of a gateway using ARP API.
 * Note that there are cases that this won't work , so 
 * there will probably have to be a usage of a function that
 * listens to the network connection and monitors the gateway IP and dest MAC.
 *
 */
bool __cdecl AdapterManager::getDestMAC(char *gatewayAddress ,unsigned int *destMAC )
{
	DWORD status;
	IPAddr destIP = inet_addr(gatewayAddress);
	ULONG   ulLen=6;
	void* voidPtr = (void*)&ulLen;
	PULONG ulongPtr = (PULONG)(voidPtr);
	void* voidPtr2 = (void*)destMAC;
	PULONG ulongPtr2 = (PULONG)(voidPtr2);
	status = SendARP(destIP , 0 , ulongPtr2 , ulongPtr);
	if (status!=NO_ERROR)
		return false;
	return true;
}
Ejemplo n.º 4
0
//Added this for use by the ping scan.  This is not thread safe with
//the main stuff, so don't call when you are listening for DHCP messages.
void ArpAndAdd (struct in_addr *paddr)
{
	 ULONG mac[2];
	 ULONG maclen = 6;

	 if(NO_ERROR == SendARP(paddr->s_addr, 0, mac, &maclen))
	 {
		struct LL_IP* pProposedIP  = DHCP_IPAllocate (DHCPDISCOVER, paddr, (unsigned char*)mac, maclen);
		if (pProposedIP)
		{
			if (pProposedIP->tAllocated==0) SetAllocTime(pProposedIP);
			ForceRenewTime(pProposedIP, 0x66666666);   //Give a bootp lease, since the device may not do dhcp      
			LOG (5, "Added lease for existing address %s", inet_ntoa (pProposedIP->dwIP));
		}
	 }
}   // ArpAndAdd
Ejemplo n.º 5
0
static BOOL Ping(VOID)
{
    LARGE_INTEGER RelativeTime;
    LARGE_INTEGER LargeTime;
    LARGE_INTEGER SentTime;
    DWORD Ret;
    BYTE TargetHW[6];
    ULONG Size;
    WCHAR Sign[2];
    WCHAR Time[100];
    WCHAR StrHwAddr[18];

    QueryTime(&SentTime);
    Size = sizeof(TargetHW);
    memset(TargetHW, 0xff, Size);
    ++Sent;
    Ret = SendARP(TargetAddr, SourceAddr, (PULONG)TargetHW, &Size);
    if (Ret == ERROR_SUCCESS)
    {
        QueryTime(&LargeTime);

        RelativeTime.QuadPart = (LargeTime.QuadPart - SentTime.QuadPart);

        if ((RelativeTime.QuadPart / TicksPerMs.QuadPart) < 1)
        {
            wcscpy(Sign, L"<");
            LoadString(GetModuleHandle(NULL), IDS_1MS, Time, sizeof(Time) / sizeof(WCHAR));
        }
        else
        {
            wcscpy(Sign, L"=");
            TimeToMsString(Time, sizeof(Time) / sizeof(WCHAR), RelativeTime);
        }

        swprintf(StrHwAddr, L"%02x:%02x:%02x:%02x:%02x:%02x", TargetHW[0], TargetHW[1],
                                                              TargetHW[2], TargetHW[3],
                                                              TargetHW[4], TargetHW[5]);
        FormatOutput(IDS_REPLY_FROM, TargetIP, StrHwAddr, Sign, Time);
        Received++;

        return TRUE;
    }

    return FALSE;
}
Ejemplo n.º 6
0
int __cdecl main(int argc, char **argv)
{
	DWORD dwRetVal;
	IPAddr DestIp = 0;
	IPAddr SrcIp = 0;       /* default for src ip */
	ULONG MacAddr[2];       /* for 6-byte hardware addresses */
	ULONG PhysAddrLen = 6;  /* default to length of six bytes */

	char *DestIpString = NULL;
	char *SrcIpString = NULL;

	BYTE *bPhysAddr;
	int i;

	if (argc > 1) {
		for (i = 1; i < argc; i++) {
			if ((argv[i][0] == '-') || (argv[i][0] == '/')) {
				switch (tolower(argv[i][1])) {
					case 'l':
						PhysAddrLen = (ULONG) atol(argv[++i]);
						break;
					case 's':
						SrcIpString = argv[++i];
						SrcIp = inet_addr(SrcIpString);
						break;
					case 'h':
					default:
						usage(argv[0]);
						break;
				}               /* end switch */
			} else
				DestIpString = argv[i];
		}                       /* end for */
	} else
		usage(argv[0]);

	if (DestIpString == NULL || DestIpString[0] == '\0')
		usage(argv[0]);

	DestIp = inet_addr(DestIpString);

	memset(&MacAddr, 0xff, sizeof (MacAddr));

	/* printf("Sending ARP request for IP address: %s\n", DestIpString); */

	dwRetVal = SendARP(DestIp, SrcIp, MacAddr, &PhysAddrLen);

	if (dwRetVal == NO_ERROR) {
		bPhysAddr = (BYTE *) & MacAddr;
		if (PhysAddrLen) {
			printf("Sending ARP request for IP address: %s\n", DestIpString); 
			for (i = 0; i < (int) PhysAddrLen; i++) {
				if (i == (PhysAddrLen - 1))
					printf("%.2X\n", (int) bPhysAddr[i]);
				else
					printf("%.2X-", (int) bPhysAddr[i]);
			}
		} else
			printf
				("Warning: SendArp completed successfully, but returned length=0\n");

	} else {
#if 0
		printf("Error: SendArp failed with error: %d", dwRetVal);
		switch (dwRetVal) {
			case ERROR_GEN_FAILURE:
				printf(" (ERROR_GEN_FAILURE)\n");
				break;
			case ERROR_INVALID_PARAMETER:
				printf(" (ERROR_INVALID_PARAMETER)\n");
				break;
			case ERROR_INVALID_USER_BUFFER:
				printf(" (ERROR_INVALID_USER_BUFFER)\n");
				break;
			case ERROR_BAD_NET_NAME:
				printf(" (ERROR_GEN_FAILURE)\n");
				break;
			case ERROR_BUFFER_OVERFLOW:
				printf(" (ERROR_BUFFER_OVERFLOW)\n");
				break;
			case ERROR_NOT_FOUND:
				printf(" (ERROR_NOT_FOUND)\n");
				break;
			default:
				printf("\n");
				break;
		}
#endif
	}

	return 0;
}
Ejemplo n.º 7
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;
}
Ejemplo n.º 8
0
DWORD InterfaceUtils::InterfaceSendARP(const char * requestAddrString) {
	DWORD dwRetVal;
	IPAddr DestIp = 0;
	IPAddr SrcIp = 0;       /* default for src ip */
	ULONG MacAddr[2];       /* for 6-byte hardware addresses */
	ULONG PhysAddrLen = 6;  /* default to length of six bytes */

	char *DestIpString = NULL;
	char *SrcIpString = NULL;

	BYTE *bPhysAddr;

	SrcIpString = "0.0.0.0";//"192.168.1.30";
	SrcIp = inet_addr(SrcIpString);
	DestIp = inet_addr(requestAddrString);

	memset(&MacAddr, 0xff, sizeof (MacAddr));

	printf("Sending ARP request for IP address: %s\n", requestAddrString);

	dwRetVal = SendARP(DestIp, SrcIp, &MacAddr, &PhysAddrLen);

	if (dwRetVal == NO_ERROR) {
		bPhysAddr = (BYTE *)& MacAddr;
		if (PhysAddrLen) {
			for (unsigned int i = 0; i < (int)PhysAddrLen; i++) {
				if (i == (PhysAddrLen - 1))
					printf("%.2X\n", (int)bPhysAddr[i]);
				else
					printf("%.2X-", (int)bPhysAddr[i]);
			}
		}
		else {
			printf("Warning: SendArp completed successfully, but returned length=0\n");
		}

		return NO_ERROR;

	}
	else {
		printf("Error: SendArp failed with error: %d", dwRetVal);
		switch (dwRetVal) {
		case ERROR_GEN_FAILURE:
			printf(" (ERROR_GEN_FAILURE)\n");
			break;
		case ERROR_INVALID_PARAMETER:
			printf(" (ERROR_INVALID_PARAMETER)\n");
			break;
		case ERROR_INVALID_USER_BUFFER:
			printf(" (ERROR_INVALID_USER_BUFFER)\n");
			break;
		case ERROR_BAD_NET_NAME:
			printf(" (ERROR_GEN_FAILURE)\n");
			break;
		case ERROR_BUFFER_OVERFLOW:
			printf(" (ERROR_BUFFER_OVERFLOW)\n");
			break;
		case ERROR_NOT_FOUND:
			printf(" (ERROR_NOT_FOUND)\n");
			break;
		default:
			printf("\n");
			break;
		}
	}
	return -1;
}
Ejemplo n.º 9
0
DWORD C_ArpTable::arpspoof_check_by_ip(IPAddr ip,PMIB_IPNETROW old_row)
{
	
	char *str1;
	in_addr ip_in_addr;
	ip_in_addr.S_un.S_addr=ip;
	str1=inet_ntoa(ip_in_addr);
	printf("Checking %s for arp spoofing...\n",str1);

	ULONG MacAddr[3],MacAddr2[3],MacAddr3[3];
	ULONG PhysAddrLen = 12,PhysAddrLen2=12,PhysAddrLen3=12;
	PMIB_IPNETROW x=C_ArpTable::find_by_ip(ip);
	if(!x || x->dwType!=3) 
		return 0; //if no entry or static entry.
	C_ArpTable::del_by_ip(ip);
	if(SendARP(ip,0, MacAddr, &PhysAddrLen)!=0)
		PhysAddrLen=0;
	C_ArpTable::del_by_ip(ip);
	if(SendARP(ip,0, MacAddr2, &PhysAddrLen2)!=0)
	{
		if(PhysAddrLen==0)
			return 0; //cant sendarp two times, exit;
		PhysAddrLen2=0;
	}
	C_ArpTable::del_by_ip(ip);
	if(SendARP(ip,0, MacAddr3, &PhysAddrLen3)!=0)
		PhysAddrLen3=0;
	if(
		(PhysAddrLen>0 &&  (PhysAddrLen!=x->dwPhysAddrLen  || memcmp(MacAddr,x->bPhysAddr,PhysAddrLen)!=0))
		||
		(PhysAddrLen2>0 && (PhysAddrLen2!=x->dwPhysAddrLen || memcmp(MacAddr2,x->bPhysAddr,PhysAddrLen2)!=0))
		||
		(PhysAddrLen3>0 && (PhysAddrLen3!=x->dwPhysAddrLen || memcmp(MacAddr3,x->bPhysAddr,PhysAddrLen3)!=0))
		)
	{

		if(
			((PhysAddrLen==0 || PhysAddrLen2==0) || (PhysAddrLen==PhysAddrLen2 && memcmp(MacAddr,MacAddr2,PhysAddrLen2)==0))
			&&
			((PhysAddrLen==0 || PhysAddrLen3==0) || (PhysAddrLen==PhysAddrLen3 && memcmp(MacAddr,MacAddr3,PhysAddrLen3)==0))
			&&
			((PhysAddrLen2==0 || PhysAddrLen3==0) || (PhysAddrLen2==PhysAddrLen3 && memcmp(MacAddr2,MacAddr3,PhysAddrLen3)==0))

			)
		{
			if(PhysAddrLen!=0)
				memcpy(x->bPhysAddr,MacAddr,PhysAddrLen);
			else
				memcpy(x->bPhysAddr,MacAddr2,PhysAddrLen2);
		}
		if(old_row)
		{
			if(
				(PhysAddrLen!=0 && old_row->dwPhysAddrLen==PhysAddrLen && memcmp(MacAddr,old_row->bPhysAddr,PhysAddrLen)==0)
				||
				(PhysAddrLen2!=0 && old_row->dwPhysAddrLen==PhysAddrLen2 && memcmp(MacAddr2,old_row->bPhysAddr,PhysAddrLen2)==0)
				||
				(PhysAddrLen3!=0 && old_row->dwPhysAddrLen==PhysAddrLen3 && memcmp(MacAddr3,old_row->bPhysAddr,PhysAddrLen3)==0)
				)
			{
				memcpy(x->bPhysAddr,old_row->bPhysAddr,old_row->dwPhysAddrLen);
				printf("use old address.\n");
			}
		}
		else
			printf("Spoofed new address.\n");
		x->dwType=4;
		C_ArpTable::del_by_ip(ip);
		if(CreateIpNetEntry(x)!=0)
		{
			C_ArpTable::del_by_ip(ip);
			CreateIpNetEntry(x);
		}

		printf("Arp spoof of %s detected. setting arp entry to static.\nfor delete static entry run \"arp -d %s\"\n\n",str1,str1);
		return 1;
		//spoofing detected!
	}
	printf("Spoofing not detected.\n\n");
	CreateIpNetEntry(x);
///	C_ArpTable::reload();
	return 0;
}
//This copies the data at requestHeader, so you can free the memory after this has been called
int RequestCommon(char * sourceIP, char * destinationIP, char * dstHostName, request_hdr_t * requestHeader, unsigned int requestSize, me_t * outboundPendingME, char * parentFuncName){
	int ret;
	unsigned short sourcePort = 0xDEAD;
	unsigned short destinationPort = 0xBEEF;
	unsigned char dstMac[6] = {0,0,0,0,0,0};
	ULONG dstMacLong[2] = {0,0};
	ULONG MACSize = 6;
	RawPacket RP;
	IPAddr srcIPAddr, dstIPAddr;

	srcIPAddr = inet_addr(sourceIP);
	dstIPAddr = inet_addr(destinationIP);

	//This is a quick hack to make it server be a bit smarter 
	//about what dst MAC is uses - gateway if the dst IP is non-local, 
	//otherwise the MAC specifically for the dst host
	//ASSUMPTION: that all hosts on the same /24 are on the same ethernet segment
	if(memcmp(&srcIPAddr, &dstIPAddr, 3) == 0){
		//send to a local host on the same ethernet segment directly
		ret = SendARP(dstIPAddr, srcIPAddr, &dstMacLong, &MACSize);
		if(ret != NO_ERROR){
			if(gUseBroadcastMAC){
				printf("%s: RequestCommon: Failed to get the MAC address for the destination host on the same local network. Defaulting to broadcast MAC\n", parentFuncName);
				memset(&dstMac, 0xFF, 6);
			}
			else{
				printf("%s: RequestCommon: Failed to get the MAC address for the destination host on the same local network. Broadcast MAC disabled, erroring out\n", parentFuncName);
				//UpdateReadinessByHostID(hostID, ARP_FAIL);
				//If we're going to error out and not send the packet, we need to delete the pending events
				//We will not delete the null measurement because it will have actually been sent
				if(strcmp("BuildNullSelfMeasurementRequestPacket", parentFuncName) != 0){
					if(strcmp("BuildSelfMeasurementRequestPacket", parentFuncName) != 0){
						ret = SelectPreviousPendingIDFromPendingME(outboundPendingME->id,outboundPendingME->nonce, &outboundPendingME->previousPendingID);
						if(ret != GENERIC_SUCCESS){
							printf("RequestCommon: SelectPreviousPendingIDFromPendingMEByID failed\n");
							return ret;
						}
						if(!gQuiet) printf("Deleting PendingMeasurementEvent id = %u\n", outboundPendingME->previousPendingID);
						DeleteFromTableByID("PendingMeasurementEvents", outboundPendingME->previousPendingID);
					}
					if(!gQuiet) printf("Deleting PendingMeasurementEvent id = %u\n", outboundPendingME->id);
					DeleteFromTableByID("PendingMeasurementEvents", outboundPendingME->id);
				
					return GENERIC_ERROR;
				}
			}
		}
		else{
			memcpy(&dstMac, &dstMacLong, 6);
		}
		RP.CreatePacket(globDeviceInfoPtr->PhysicalAddress, dstMac,
						inet_addr(sourceIP),inet_addr(destinationIP),sourcePort,destinationPort,
						(UCHAR*)requestHeader, requestSize);
	}
	else{
		//send to a non-local host, by way of the gateway
		RP.CreatePacket(globDeviceInfoPtr->PhysicalAddress, globDeviceInfoPtr->GatewayPhysicalAddress,
						inet_addr(sourceIP),inet_addr(destinationIP),sourcePort,destinationPort,
						(UCHAR*)requestHeader, requestSize);
	}

	RP.SendPacket(globDevice);

	return GENERIC_SUCCESS;
}
Ejemplo n.º 11
0
struct netif *netif_open(int timeout_ms)
{
    int inum = 0;
    int i = 0, total_interfaces = 0;
    struct netif *netif;
    IP_ADAPTER_INFO *AdapterInfo;
    IP_ADAPTER_INFO *Current;
    ULONG AIS;
    DWORD status;

    netif = (struct netif *)calloc(1, sizeof(struct netif));

    /* Retrieve the device list on the local machine */
    if (pcap_findalldevs(&netif->alldevs, netif->errbuf) == -1) {
        printf("Error finding interfaces\n");
        goto error_return;
    }

    /* Print the list */
    for (netif->d = netif->alldevs; netif->d; netif->d = netif->d->next) {
        /*printf("%d. %s", ++i, d->name); */
        printf("%d", ++i);
        if (netif->d->description)
            printf(" (%-70s)\n", netif->d->description);
        else
            printf(" (No description available)\n");
    }
    total_interfaces = i;

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

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

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

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

    /* Open the device */
    if ((netif->pcap_interface = pcap_open_live(netif->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
                                 1,	// promiscuous mode
                                 timeout_ms,	// read timeout in ms
                                 netif->errbuf	// error buffer
                                               )) == NULL) {
        fprintf(stderr,
                "\nUnable to open the adapter. %s is not supported by WinPcap\n",
                netif->d->name);
        /* Free the device list */
        pcap_freealldevs(netif->alldevs);
        goto error_return;
    }

    /* lookup ip address */
    AdapterInfo =
        (IP_ADAPTER_INFO *) calloc(total_interfaces,
                                   sizeof(IP_ADAPTER_INFO));
    AIS = sizeof(IP_ADAPTER_INFO) * total_interfaces;
    status = GetAdaptersInfo(AdapterInfo, &AIS);
    if (status != ERROR_SUCCESS) {
        fprintf(stderr,
                "\nError, GetAdaptersInfo() call in netif_win32_pcap.c failed\n");
        free(AdapterInfo);
        goto error_return;
    }

    for (Current = AdapterInfo; Current != NULL; Current = Current->Next) {
        if (strstr(netif->d->name, Current->AdapterName) != 0) {
            uint32_t my_ip;
            ULONG len;
            uint8_t tmp[16];

            my_ip =
                inet_addr(Current->IpAddressList.IpAddress.String);
            len = sizeof(tmp);
            SendARP(my_ip, INADDR_ANY, tmp, &len);
            memcpy(netif->mac, &tmp[0], sizeof(netif->mac));
        }
    }
    free(AdapterInfo);
    return netif;

error_return:
    free(netif);
    return NULL;
}
Ejemplo n.º 12
0
int ProcessDHCPMessage (struct dhcp_packet *pDhcpPkt, int *pSize)
{
unsigned char *p=NULL;
struct LL_IP  *pCurIP=NULL, *pProposedIP=NULL;	// Thanks Sam Leitch !
int            Ark, nDhcpType = 0;
struct in_addr sRequestedAddr;
DWORD sStaticIP;

    if (IsDHCP (*pDhcpPkt))
    {
       // search DHCP message type
       p = DHCPSearchOptionsField (pDhcpPkt->options, DHO_DHCP_MESSAGE_TYPE, NULL);
       if (p!=NULL)        nDhcpType = *p;
     }
    if (pDhcpPkt->yiaddr.s_addr!=INADDR_ANY  &&  pDhcpPkt->yiaddr.s_addr!=INADDR_NONE )
            return FALSE ; // address already assigned

     // the tab has one undef raw
     for (Ark=0 ; Ark<SizeOfTab(tDHCPType)-1 && nDhcpType!=tDHCPType[Ark].nType ; Ark++) ;
     LOG (5, "Rcvd %s Msg for IP %s, Mac %s",
                      tDHCPType[Ark].sType,
                      inet_ntoa (pDhcpPkt->ciaddr),
                      haddrtoa(pDhcpPkt->chaddr, pDhcpPkt->hlen,':'));


    // if (sParamDHCP.nPoolSize==0) return FALSE;   // no allocation pool --> listen only

     switch (nDhcpType)
     {
        case 0           :    // BootP
            if(sParamDHCP.nIgnoreBootp)
            {
               LOG (5, "Ignoring Bootp request");
               break;
            }
        case DHCPDISCOVER :
            sStaticIP = DHCP_StaticAssignation (pDhcpPkt);
			if (sStaticIP != INADDR_NONE)
			{
               LOG (0, "%s: statically assigned to address %s", 
								haddrtoa(pDhcpPkt->chaddr, pDhcpPkt->hlen,':'), 
								inet_ntoa (* (struct in_addr *) & sStaticIP) );
               pDhcpPkt->yiaddr.s_addr = sStaticIP;
			}
			else
			{
               p  = DHCPSearchOptionsField (pDhcpPkt->options, DHO_DHCP_REQUESTED_ADDRESS, NULL);
               if (p!=NULL)
              {
                   pDhcpPkt->ciaddr = * (struct in_addr *) p;
                   LOG (5, "Client requested address %s", inet_ntoa (pDhcpPkt->ciaddr));
              }
              pProposedIP  = DHCP_IPAllocate (nDhcpType, & pDhcpPkt->ciaddr, pDhcpPkt->chaddr, pDhcpPkt->hlen);
              if (pProposedIP == NULL)
              {
                  LOG (1, "no more address or address previously allocated by another server");
                  return FALSE;
              }
              pDhcpPkt->yiaddr.s_addr = pProposedIP->dwIP.s_addr;
              LOG (2, "%s: proposed address %s", IsDHCP(*pDhcpPkt) ? "DHCP" : "BOOTP", inet_ntoa (pProposedIP->dwIP) );

              //If this is a bootp, there is no other response from the client.  
              //Since we don't want leases expiring (or being mistaken for unAcked DHCP offers),
              //set renewed to a distant time
              if(nDhcpType == 0  &&  sStaticIP == INADDR_NONE)     // patched by Rolf Offermanns
                  ForceRenewTime(pProposedIP, 0x66666666);         // fixed by Sam Leitch
            } // dynamically assigned address

            // populate the packet to be returned
            pDhcpPkt->op = BOOTREPLY;
            // translate $IP$ and $MAC$ from boot file name
            TranslateExp (sParamDHCP.szBootFile, pDhcpPkt->file, pDhcpPkt->yiaddr, pDhcpPkt->chaddr);
           *pSize = DHCPOptionsReply (pDhcpPkt, DHCPOFFER);
            break ;

		//NJW Changed how requests are handled to mimic linux -- requests are responded to even if we didn't originally allocate, but only if the requested address is in our pool range

        case DHCPREQUEST :
         {BOOL bSERVER = FALSE;  // TRUE if Tftpd32 has assigned this address
           // Static Allocation ?
             // search field REQUEST ADDR in options
            sStaticIP = DHCP_StaticAssignation (pDhcpPkt);
			if (sStaticIP != INADDR_NONE)
			{
			    // populate the packet to be returned
                   pDhcpPkt->op = BOOTREPLY;
                   pDhcpPkt->yiaddr.s_addr = sStaticIP;
                 // translate $IP$ and $MAC$ from boot file name
                 TranslateExp (sParamDHCP.szBootFile, pDhcpPkt->file, pDhcpPkt->yiaddr, pDhcpPkt->chaddr);
                   *pSize = DHCPOptionsReply (pDhcpPkt, DHCPACK);
				   break;
			}

           // has tftpd32 dinamically assigned this address
           pCurIP = DHCPSearchByMacAddress (pDhcpPkt->chaddr, pDhcpPkt->hlen);
           if (pCurIP==NULL)  return FALSE; // not attributed by Tftpd32 --> do not answer
           // search field REQUEST ADDR in options
            // if specified should fit database
			p  = DHCPSearchOptionsField (pDhcpPkt->options, DHO_DHCP_REQUESTED_ADDRESS, NULL);
            if (p!=NULL)
			{
				pDhcpPkt->ciaddr = * (struct in_addr *) p;
			}

			if(AddrFitsPool(&pDhcpPkt->ciaddr))
			{
				//Look up the address, if it's not found, or the owner is this macaddr,
				//or the lease was expired, allow the serving.
				BOOL wasexpired = FALSE;
				pProposedIP = DHCPSearchByIP(&pDhcpPkt->ciaddr, &wasexpired);
				bSERVER = !pProposedIP || wasexpired || (0 == memcmp(pProposedIP->sMacAddr, pDhcpPkt->chaddr, 6));
			}

			if (bSERVER)
			{

				pProposedIP  = DHCP_IPAllocate (nDhcpType, & pDhcpPkt->ciaddr, pDhcpPkt->chaddr, pDhcpPkt->hlen);
				if (pProposedIP == NULL)
				{
					  LOG (1, "no more addresses or address previously allocated by another server");
					  return FALSE;
				}
				if (pProposedIP->tAllocated==0) SetAllocTime(pProposedIP);
				SetRenewTime(pProposedIP);
				LOG (5, "Previously allocated address %s acked", inet_ntoa (pProposedIP->dwIP));
				// populate the packet to be returned
				pDhcpPkt->op = BOOTREPLY;
				pDhcpPkt->yiaddr.s_addr = pProposedIP->dwIP.s_addr;
                TranslateExp (sParamDHCP.szBootFile, pDhcpPkt->file, pDhcpPkt->yiaddr, pDhcpPkt->chaddr);
				*pSize = DHCPOptionsReply (pDhcpPkt, DHCPACK);
			}
			else
			{
				LOG (5, "Client requested address %s which was not allocated by tftpd32 and is either outside our pool or is used by someone else",
							  inet_ntoa (pDhcpPkt->ciaddr) );
				return FALSE ; // do not answer
 			}
           } // Block for bSERVER declaration
           break;


        case DHCPDECLINE :
             // search current item and its precedent
          pCurIP = DHCPSearchByMacAddress (pDhcpPkt->chaddr, pDhcpPkt->hlen);
           if (pCurIP!=NULL)
           {
             p  = DHCPSearchOptionsField (pDhcpPkt->options, DHO_DHCP_REQUESTED_ADDRESS, NULL);
             if (p!=NULL) 
              {
                 sRequestedAddr.s_addr = * (DWORD *) p;
                 if ( pCurIP->dwIP.s_addr==sRequestedAddr.s_addr) 
                 {
                     DHCPDestroyItem (pCurIP);
                     LOG (5, "item destroyed");
                 }
             }
           }
		   //The decline is sent when an address is already in use.  Do an ARP and 
		   //add a lease for the in-use address
		   {
			 ULONG mac[2];
			 ULONG maclen = 6;
			// search field REQUEST ADDR in options
			// if specified should fit database
			p  = DHCPSearchOptionsField (pDhcpPkt->options, DHO_DHCP_REQUESTED_ADDRESS, NULL);
			if (p!=NULL)
			{
				pDhcpPkt->ciaddr = * (struct in_addr *) p;
			}

			 if(NO_ERROR == SendARP(pDhcpPkt->ciaddr.s_addr, 0, mac, &maclen))
			 {
				pProposedIP  = DHCP_IPAllocate (nDhcpType, & pDhcpPkt->ciaddr, (unsigned char*)mac, maclen);
				if (pProposedIP)
				{
					if (pProposedIP->tAllocated==0) SetAllocTime(pProposedIP);
					ForceRenewTime(pProposedIP, 0x66666666);   //Give a bootp lease, since the device may not do dhcp      
					LOG (5, "Added lease for existing address %s", inet_ntoa (pProposedIP->dwIP));
				}
			 }
		   }
           break;

        case DHCPRELEASE :
            // do not destroy the item but mark it free
           pCurIP = DHCPSearchByMacAddress (pDhcpPkt->chaddr, pDhcpPkt->hlen);
           if (pCurIP!=NULL) // then mac address found in table
           {
                ZeroAllocTime(pCurIP);
                ZeroRenewTime(pCurIP);
                LOG (5, "item %s released", haddrtoa(pDhcpPkt->chaddr, pDhcpPkt->hlen,':') );
           }
           break;
       } // switch type


DHCPScan();

// answer only to BootP, Request or discover msg
return  (nDhcpType==0 || nDhcpType==DHCPDISCOVER || nDhcpType==DHCPREQUEST);
} // ProcessDHCPMessage
Ejemplo n.º 13
0
int GetMacByARP(char * DestIpString, char * DestMacString)
{
	DWORD dwRetVal = 0;
    IPAddr DestIp = 0;
    IPAddr SrcIp = 0; /* default for src ip */
	ULONG MacAddr[2] = {0}; /* for 6-byte hardware addresses */
    ULONG PhysAddrLen = 6; /* default to length of six bytes */

    char *SrcIpString = NULL;

    BYTE *bPhysAddr;
    int i;

    DestIp = inet_addr(DestIpString);
	
	// printf("Sending ARP request for IP address: %s\n", DestIpString);
	
	PhysAddrLen = sizeof(MacAddr);
	memset(&MacAddr, 0xff, sizeof (MacAddr));
    dwRetVal = SendARP(DestIp, SrcIp, (PULONG)&MacAddr, &PhysAddrLen);
    if (dwRetVal == NO_ERROR) 
	{
        bPhysAddr = (BYTE *) &MacAddr;
        if (PhysAddrLen) 
		{
            for (i = 0; i < (int) PhysAddrLen; i++) 
			{
				sprintf(DestMacString + i*2, "%.2X", (int) bPhysAddr[i]);
            }
        }
		
		return 0;
		/*
		else
		{
            printf("Warning: SendArp completed successfully, but returned length=0\n");
		}
		*/
    } 
	else 
	{
        printf("Error: SendArp failed with error: %d", dwRetVal);
        switch (dwRetVal)
		{
        case ERROR_GEN_FAILURE:
            printf(" (ERROR_GEN_FAILURE)\n");
            break;
        case ERROR_INVALID_PARAMETER:
            printf(" (ERROR_INVALID_PARAMETER)\n");
            break;
        case ERROR_INVALID_USER_BUFFER:
            printf(" (ERROR_INVALID_USER_BUFFER)\n");
            break;
        case ERROR_BAD_NET_NAME:
            printf(" (ERROR_GEN_FAILURE)\n");
            break;
        case ERROR_BUFFER_OVERFLOW:
            printf(" (ERROR_BUFFER_OVERFLOW)\n");
            break;
        case ERROR_NOT_FOUND:
            printf(" (ERROR_NOT_FOUND)\n");
            break;
        default:
            printf("\n");
            break;
        }
		return dwRetVal;
    }
}
DWORD WINAPI IcmpWrongPortScan (LPVOID pPar)
{
	ThreadSyn cSynEntry;
	SetBoolTrue cSBT(&bIcmpSending);
	DWORD dwThreadId;
	CreateThread(NULL,0,IcmpReceiver,pPar,0,&dwThreadId);;

	pcap_if_t *pSelectDev;
	ThreadParament * pThreadParament=(ThreadParament *)pPar;
	pSelectDev=pThreadParament->SelectDev;
	pcap_t *fp;
	char error[256];
	char bDestMac[6];
	memset(bDestMac,0xff,6);

	UdpPacket thePacket;

	DWORD dwNetMask=pThreadParament->dwNetMAsk;
	DWORD dwDefaultGatewayIp=pThreadParament->dwDefaultGateway;
	ULONG bGatewayMac[2];
	ULONG ulLen=6;
	SendARP (htonl(dwDefaultGatewayIp), 0, bGatewayMac, &ulLen);
	memcpy(thePacket.theEthHead.bDestMac,bGatewayMac,6);
	memcpy(thePacket.theEthHead.bSourceMac,pThreadParament->HostMac,6);
	thePacket.theEthHead.usEthernetType=0x8;
	thePacket.theIpHead.ucVersionAndHeadLength=0x45;
	thePacket.theIpHead.ucTos=0;
	thePacket.theIpHead.usTotalLength=htons(30);
	thePacket.theIpHead.usIdentification=1234;
	thePacket.theIpHead.usFlagsAndFragmentOffset=0;
	thePacket.theIpHead.ucTtl=119;
	thePacket.theIpHead.ucProtocol=17;//udp
	thePacket.theIpHead.dwSourceAddr=htonl(pThreadParament->dwHostIP);
	
	thePacket.theUdpHead.usSourcePort=ntohs(12345);
	thePacket.theUdpHead.usDestPort=ntohs(567);
	thePacket.theUdpHead.usLength=ntohs(10);
	thePacket.theUdpHead.usData=0x6664;


	UdpFakeHeader theFakeHeader;
	theFakeHeader.bZero=0;
	theFakeHeader.bUdpLength=htons(sizeof(UdpHead));
	theFakeHeader.bProtocolType=17;
	theFakeHeader.dwSourceAddr=htonl(pThreadParament->dwHostIP);
	
	if((fp = pcap_open_live(pSelectDev->name, 65536, 1, 1000, error) ) == NULL)
	{
		return 0;
	}
	for(DWORD dwIP=pThreadParament->dwOriginalIP;dwIP<=pThreadParament->dwLastIP&&!bStop;dwIP++)
	{
		char  strLog[256];
		in_addr tmp;
		tmp.S_un.S_addr=htonl(dwIP);
		sprintf(strLog,"Scaning Host %s.",inet_ntoa(tmp));
		pMainWindow->SendMessage(WM_UPDATA_LOG,(WPARAM)strLog);
		if((dwIP&dwNetMask)==(dwDefaultGatewayIp&dwNetMask))
		{
			ulLen=6;
			ULONG bHostMac[2];
			
			if(SendARP(htonl(dwIP),0,bHostMac,&ulLen)!=NO_ERROR)
			{
				continue;
			}
			memcpy(thePacket.theEthHead.bDestMac,bHostMac,6);

		}
		thePacket.theIpHead.dwDestAddr=htonl(dwIP);
		
		thePacket.theIpHead.usCrc=0;
		thePacket.theIpHead.usCrc=CheckSum((USHORT*)(&(thePacket.theIpHead)),sizeof(IpHead));
		
		thePacket.theUdpHead.usCrc=0;
		theFakeHeader.dwDestAddr=htonl(dwIP);
		thePacket.theUdpHead.usCrc=UdpCheckSum((char *)&(thePacket.theUdpHead),(char *)&theFakeHeader,sizeof(UdpHead));

		if(pcap_sendpacket(fp,(u_char *)(&thePacket),sizeof(thePacket))!=0)
		{
			pMainWindow->MessageBox("Send Data Error!");
		}
		while(bPause)
		{
			Sleep(100);
		}

	}
	return 0;
}
DWORD WINAPI TcpSynScan(LPVOID pPar)
{
	ThreadSyn cSynEntry;
	SetBoolTrue cSBT(&bSynSending);
	DWORD dwThreadId;
	CreateThread(NULL,0,TcpReceiver,pPar,0,&dwThreadId);
	
	pcap_if_t *pSelectDev;
	ThreadParament * pThreadParament=(ThreadParament *)pPar;
	pSelectDev=pThreadParament->SelectDev;
	pcap_t *fp;
	char error[256];
	char bDestMac[6];
	memset(bDestMac,0xff,6);

	TcpPacket thePacket;

	DWORD dwNetMask=pThreadParament->dwNetMAsk;
	DWORD dwDefaultGatewayIp=pThreadParament->dwDefaultGateway;
	ULONG bGatewayMac[2];
	ULONG ulLen=6;
	if(SendARP(htonl(dwDefaultGatewayIp),0,bGatewayMac,&ulLen)!=NO_ERROR)
	{	
		return 0;
	}
	memcpy(thePacket.theIpPacket.theEthHead.bDestMac,bGatewayMac,6);
	memcpy(thePacket.theIpPacket.theEthHead.bSourceMac,pThreadParament->HostMac,6);
	thePacket.theIpPacket.theEthHead.usEthernetType=0x8;
	thePacket.theIpPacket.theIpHead.ucVersionAndHeadLength=0x45;
	thePacket.theIpPacket.theIpHead.ucTos=0;
	thePacket.theIpPacket.theIpHead.usTotalLength=htons(48);;
	thePacket.theIpPacket.theIpHead.usIdentification=1234;
	thePacket.theIpPacket.theIpHead.usFlagsAndFragmentOffset=0;
	thePacket.theIpPacket.theIpHead.ucTtl=119;
	thePacket.theIpPacket.theIpHead.ucProtocol=6;//tcp
	thePacket.theIpPacket.theIpHead.dwSourceAddr=htonl(pThreadParament->dwHostIP);
	
	thePacket.theTcpHead.usSourcePort=htons(12345);
	thePacket.theTcpHead.dwSeq=ntohl(198327);
	thePacket.theTcpHead.dwAck=0;
	thePacket.theTcpHead.ucLength=0x70;
	thePacket.theTcpHead.ucFlag=2;
	thePacket.theTcpHead.usWindow=0xFFFF;	 //16 位窗口大小
	thePacket.theTcpHead.usCrc=0;//16 位校验和
	thePacket.theTcpHead.usUrgent=0;//16 位紧急数据偏移量
	thePacket.theTcpHead.unMssOpt=htonl(0x020405B4);
	thePacket.theTcpHead.usNopOpt= 0x0101;
	thePacket.theTcpHead.usSackOpt= 0x0204;

	TcpFakeHeader theFakeHeader;
	theFakeHeader.bZero=0;
	theFakeHeader.bTcpLength=htons(28);
	theFakeHeader.bProtocolType=6;
	theFakeHeader.dwSourceAddr=htonl(pThreadParament->dwHostIP);
	if((fp = pcap_open_live(pSelectDev->name, 65536, 1, 1000, error) ) == NULL)
	{
		return 0;
	}
	for(DWORD dwIP=pThreadParament->dwOriginalIP;dwIP<=pThreadParament->dwLastIP&&!bStop;dwIP++)
	{
		char  strLog[256];
		in_addr tmp;
		tmp.S_un.S_addr=htonl(dwIP);
		sprintf(strLog,"Scaning Host %s.",inet_ntoa(tmp));
		pMainWindow->SendMessage(WM_UPDATA_LOG,(WPARAM)strLog);
		if((dwIP&dwNetMask)==(dwDefaultGatewayIp&dwNetMask))
		{
			ulLen=6;
			ULONG bHostMac[2];
			
			if(SendARP(htonl(dwIP),0,bHostMac,&ulLen)!=NO_ERROR)
			{
				continue;
			}
			memcpy(thePacket.theIpPacket.theEthHead.bDestMac,bHostMac,6);

		}
		thePacket.theIpPacket.theIpHead.dwDestAddr=htonl(dwIP);
		
		for(DWORD dwPort=pThreadParament->dwOriginalPort;dwPort<=pThreadParament->dwLastPort&&!bStop;dwPort++)
		{
			thePacket.theTcpHead.usDestPort=htons((WORD)dwPort);
			thePacket.theIpPacket.theIpHead.usCrc=0;
			thePacket.theIpPacket.theIpHead.usCrc=CheckSum((const char *)(&(thePacket.theIpPacket.theIpHead)),sizeof(IpHead));
			thePacket.theTcpHead.usCrc=0;
			theFakeHeader.dwDestAddr=htonl(dwIP);
			thePacket.theTcpHead.usCrc=TcpCheckSum((char *)&(thePacket.theTcpHead),(char *)&(theFakeHeader),28);
		
			if(pcap_sendpacket(fp,(u_char *)(&thePacket),sizeof(TcpPacket))!=0)
			{
				pMainWindow->MessageBox("Send Data Error!");
			}
			while(bPause)
			{
				Sleep(100);
			}
		}
	}
	return 0;
}
Ejemplo n.º 16
0
int GetIFCDetails(char *pIFCName, PSCANPARAMS pScanParams)
{
  int lRetVal = 0;
  unsigned long lLocalIPAddr = 0;
  unsigned long lGWIPAddr = 0;
  ULONG lGWMACAddr[2];
  ULONG lGWMACAddrLen = 6;
  PIP_ADAPTER_INFO lAdapterInfoPtr = NULL;
  PIP_ADAPTER_INFO lAdapter = NULL;
  DWORD lFuncRetVal = 0;
  ULONG lOutBufLen = sizeof (IP_ADAPTER_INFO);


  if ((lAdapterInfoPtr = (IP_ADAPTER_INFO *) HeapAlloc(GetProcessHeap(), 0, sizeof (IP_ADAPTER_INFO))) == NULL)
  {
    LogMsg("getIFCDetails() : Error allocating memory needed to call GetAdaptersinfo\n");
    lRetVal = 1;
    goto END;
  } // if ((lAdapterInfo...


  if (GetAdaptersInfo(lAdapterInfoPtr, &lOutBufLen) == ERROR_BUFFER_OVERFLOW) 
  {
    HeapFree(GetProcessHeap(), 0, lAdapterInfoPtr);
    if ((lAdapterInfoPtr = (IP_ADAPTER_INFO *) HeapAlloc(GetProcessHeap(), 0, lOutBufLen)) == NULL)
    {
      LogMsg("getIFCDetails() : Error allocating memory needed to call GetAdaptersinfo");
      lRetVal = 2;
      goto END;
    } // if ((lAdap...
  } // if (GetAdapte...



  /*
   *
   *
   */
  if ((lFuncRetVal = GetAdaptersInfo(lAdapterInfoPtr, &lOutBufLen)) == NO_ERROR) 
  {
    for (lAdapter = lAdapterInfoPtr; lAdapter; lAdapter = lAdapter->Next)
    {
      if (StrStrI(pIFCName, lAdapter->AdapterName))
	     {
        // Get local MAC address
        CopyMemory(pScanParams->LocalMAC, lAdapter->Address, BIN_MAC_LEN);

        // Get local IP address
        lLocalIPAddr = inet_addr(lAdapter->IpAddressList.IpAddress.String);
        CopyMemory(pScanParams->LocalIP, &lLocalIPAddr, 4);


      		// Get gateway IP address
        lGWIPAddr = inet_addr(lAdapter->GatewayList.IpAddress.String);
        CopyMemory(pScanParams->GWIP, &lGWIPAddr, 4);


        // Get gateway MAC address
        CopyMemory(pScanParams->GWIP, &lGWIPAddr, 4); // ????
        ZeroMemory(&lGWMACAddr, sizeof(lGWMACAddr));
        SendARP(lGWIPAddr, 0, lGWMACAddr, &lGWMACAddrLen);
        CopyMemory(pScanParams->GWMAC, lGWMACAddr, 6);

		      // Get interface index.
		      pScanParams->Index = lAdapter->Index;

		      // Get interface description
		      CopyMemory(pScanParams->IFCDescr, lAdapter->Description, sizeof(pScanParams->IFCDescr) - 1);

        break;
	     } // if (StrSt...
    } // for (lAdapt...


  }
  else
  {
    lRetVal = 1;
  } // if ((lFunc...

END:
  if (lAdapterInfoPtr)
    HeapFree(GetProcessHeap(), 0, lAdapterInfoPtr);


  return(lRetVal);
}