关于TCP/UDP的包过滤函数

来源:互联网 发布:kevin macleod 知乎 编辑:程序博客网 时间:2024/05/21 17:48


//包过滤函数
FORWARD_ACTION FilterPacket(
unsignedchar *PacketHeader,
unsignedchar *Packet,
unsignedint   PacketLength,
DIRECTION_E   direction,
unsignedint   RecvInterfaceIndex,
unsignedint   SendInterfaceIndex)
{  
    //提取IP头
    IPheader *pIPHdr=(IPHeader *) PacketHeader;
    TCPHeader *pTCPHdr=NULL:
    UDPHeader *PUDPHdr=NULL:
    if(PIPHdr->ipProtocol==6)  //是TCP协议
    {

        pTCPHdr=(TCPHeader*)Packet;   //提取TCP头
       if(!(pTCPHdr->falgs&0x02))
       {
           return FORWARD;
       }
    }
    //与过滤规则相比较,决定采取的行动
   CFilterList *pList=g_pHeader;
   while(pList!=NULL)
   {
    //比较协议
    if(pList->ipf.protocol==0||pList->ipf.protocol==pIPhdr->ipProtocol)
    {  
        //查看源IP地址
        if(pList->ipf.sourceIP!=0&(pList->ipf.sourceIP&pList->ipf.sourceMask)!=pIPHdr->ipSource)
        {
            pList=pList->pNext;
            continue;
        }
        //查看目的IP地址
        if(pList->ipf.destinationIP!=0&(pList->ipf.destinationIP&pList->ipf.destinationMask)!=pIPHdr->ipDestination)
        {
            pList=pList->pNext;
            continue;
        }
    }
    //如果为TCP封包,查看端口号
   if(pIPHdr->ipProtocol==6)
   {

    pTCPHdr=(TCPHeader*)Packet;
   if(pList->ipf.sourcePort==0||pList->ipf.sourcePort==pTCPHdr->sourcePort)
   {
    if(pList->ipf.destinationPort==0||pList->ipf.destinationPort==pTCPHdr->destinationPort)
    {
        if(pList->ipf.bDrop)
            return DROP;
         else
            return FORWARD;
    }
   }
   }
    //如果是UDP封包,查看端口号
   else if(pIPHdr->ipProtocol==17)
      {

       pUDPHdr=(UDPHeader*)Packet;
      if(pList->ipf.sourcePort==0||pList->ipf.sourcePort==pUDPHdr->sourcePort)
      {
       if(pList->ipf.destinationPort==0||pList->ipf.destinationPort==pUDPHdr->destinationPort)
       {
           if(pList->ipf.bDrop)
               return DROP;
            else
               return FORWARD;
       }
      }
      }
   //其他封包直接处理
    else
    {
        if(pList->ipf.bDrop)
               return DROP;
            else
               return FORWARD;
    }

   }
   //比较下一规则
    pList=pList->pNext;
}
 return FORWARD;
 }

0 0
原创粉丝点击