/*************************************************************
*function : 将16进制IP地址转变成十进制IP地址串
*paramters:
*author : rex
*date : 2010-10-25
*modify :
**************************************************************/
void hex2ip(unsigned int ipaddr, char *ipbuf)
{
char *ip;
ip = (char *)&ipaddr;
sprintf(ipbuf, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
}
/*************************************************************
*function : 处理钩子函数抓取的IP数据包
*paramters:
struct ifnet *pIf, /@ interface that received the packet @/
struct mbuf **pPtrMbuf, /@ pointer to pointer to an mbuf chain @/
struct ip **pPtrIpHdr, /@ pointer to pointer to IP header @/
int ipHdrLen, /@ IP packet header length @/
*author : rex
*date : 2010-10-26
*modify :
**************************************************************/
BOOL ipFilterHook(struct ifnet *pIf, struct mbuf **pPtrMbuf, struct ip **pPtrIpHdr, int ipHdrLen)
{
struct ip *pIpHead;
struct udphdr *pUdpHead;
struct tcphdr *pTcpHead;
char srcIpaddr[17];
char dstIpaddr[17];
char str[1500];
unsigned short udpPacketLen;
int i;
M_BLK_ID pMblk = *pPtrMbuf;
pIpHead = (struct ip *)pMblk->mBlkHdr.mData;
/* output the src and des ip addr */
hex2ip(pIpHead->ip_src.s_addr, srcIpaddr);
hex2ip(pIpHead->ip_dst.s_addr, dstIpaddr);
if (!strcmp(dstIpaddr, "255.255.255.255")) /* 屏蔽广播包 */
return (FALSE);
printf("srcIp:%s\t dstIp:%s\r\n", srcIpaddr, dstIpaddr); /* 打印IP包中源IP地址和目的IP地址 */
switch(pIpHead->ip_p)
{
case IPPROTO_ICMP:
printf("protocol icmp\r\n");
break;
case IPPROTO_TCP:
pTcpHead = (struct tcphdr*)(pMblk->mBlkHdr.mData + ipHdrLen);
printf("protocol tcp\r\n");
break;
case IPPROTO_UDP:
pUdpHead = (struct udphdr*)(pMblk->mBlkHdr.mData + ipHdrLen);
udpPacketLen = ntohs(pUdpHead->uh_ulen);
memcpy(str, ((char *)pMblk->mBlkHdr.mData + ipHdrLen + sizeof(struct udphdr)), udpPacketLen);
printf("srcport:%u\t, dstport:%u\t, len:%u\r\n", ntohs(pUdpHead->uh_sport), ntohs(pUdpHead->uh_dport), udpPacketLen);
for (i = 0; i < udpPacketLen; i++) /* 打印udp数据包中的内容*/
{
printf("%2x", str[i]);
if ( i%16 == 0)
printf("\r\n");
}
printf("\r\n\r\n");
break;
default:
printf("unknow protocol %d\r\n", pIpHead->ip_p);
break;
}
return (FALSE);
}
/*************************************************************
*function : 抓取网口收到的IP包
*paramters:
*author : rex
*date : 2010-10-25
*modify :
**************************************************************/
void catchPacketFunc()
{
if (ipFilterHookAdd(ipFilterHook) == ERROR)
perror("ipFilterHookAdd failed\r\n");
}
|