首页 > 代码库 > 包分析(原始套接字七)

包分析(原始套接字七)

紧接上节,DecodeIpPack()函数完成包的解析:

//IP包解析
int DecodeIpPack(char *buf, int iBufSize)
{
 IP_HEADER *pIpheader;
 int iProtocol, iTTL;
 char szProtocol[MAX_PROTO_TEXT_LEN];
 char szSourceIP[MAX_ADDR_LEN], szDestIP[MAX_ADDR_LEN];
 SOCKADDR_IN saSource, saDest;
 pIpheader = (IP_HEADER*)buf;
 //Check Proto
 iProtocol = pIpheader->proto;
 strncpy(szProtocol, CheckProtocol(iProtocol), MAX_PROTO_TEXT_LEN);
 if ((iProtocol == IPPROTO_TCP) && (!ParamTcp))
  return true;
 if ((iProtocol == IPPROTO_UDP) && (!ParamUdp))
  return true;
 if ((iProtocol == IPPROTO_ICMP) && (!ParamIcmp))
  return true;
 //Check Source IP
 saSource.sin_addr.s_addr = pIpheader->sourceIP;
 strncpy(szSourceIP, inet_ntoa(saSource.sin_addr), MAX_ADDR_LEN);
 if (strFromIpFilter)
 if (strcmp(strFromIpFilter, szSourceIP))
  return true;
 //Check Dest IP
 saDest.sin_addr.s_addr = pIpheader->destIP;
 strncpy(szDestIP, inet_ntoa(saDest.sin_addr), MAX_ADDR_LEN);
 if (strDestIpFilter)
  if (strcmp(strDestIpFilter, szDestIP))
   return true;
  iTTL = pIpheader->ttl;
  //Output
  printf("%s ", szProtocol);
  printf("%s->%s ", szSourceIP, szDestIP);
  printf("bytes=%d TTL=%d ", iBufSize, iTTL);
  //Calculate IP Header Length
  int iIphLen = sizeof(unsigned long)*(pIpheader->h_lenver &0xf);
  //Decode Sub Protocol:TCP, UDP, ICMP, etc
 switch (iProtocol)
 {
  case IPPROTO_TCP:
   DecodeTcpPack(buf + iIphLen);
   break;
  case IPPROTO_UDP:
   DecodeUdpPack(buf + iIphLen);
   break;
  case IPPROTO_ICMP:
   DecodeIcmpPack(buf + iIphLen);
   break;
  default:
   break;
 }
 return true;
}


  上述程序解析IP包类型后又分别调用DecodeTcpPack()、DecodeUdpPack()、DecodeIcmpPack()解析相应的TCP报文、UDP报文和ICMP报文。

//TCP报文解析
int DecodeTcpPack(char *TcpBuf)
{
 TCP_HEADER *pTcpHeader;
 int i;
 pTcpHeader = (TCP_HEADER*)TcpBuf;
 printf("Port:%d->%d ", ntohs(pTcpHeader->th_sport), ntohs(pTcpHeader->th_dport));
 unsigned char FlagMask = 1;
 for (i = 0; i < 6; i++)
 {
  if ((pTcpHeader->th_flag) &FlagMask)
   printf("%c", TcpFlag[i]);
  else
   printf("-");
  FlagMask = FlagMask << 1;
 }
 printf("\n");
 return true;

//UDP报文解析
int DecodeUdpPack(char *UdpBuf)
{
 UDP_HEADER *pUdpHeader;
 pUdpHeader = (UDP_HEADER*)UdpBuf;
 printf("Port:%d->%d ", ntohs(pUdpHeader->uh_sport), ntohs(pUdpHeader->uh_dport));
 printf("Len=%d\n", ntohs(pUdpHeader->uh_len));
 return true;
}

//ICMP报文解析 
int DecodeIcmpPack(char *IcmpBuf)
{
 ICMP_HEADER *pIcmpHeader;
 pIcmpHeader = (ICMP_HEADER*)IcmpBuf;
 printf("Type:%d,%d ", pIcmpHeader->i_type, pIcmpHeader->i_code);
 printf("ID=%d SEQ=%d\n", pIcmpHeader->i_id, pIcmpHeader->i_seq);
 return true;
}


  上述程序分析了具体的TCP、UDP和ICMP报头,解析出源地址、目标地址、源端口、目标端口、ICMP控制信息类型和代码等。当然,我们也可以进一步分析报文的数据域,或进行应用层解析,从而可获知任何信息(如果信息未采用任何加密手段),包括:

  1. 局域网上的其他用户在访问什么网站; 

  2. 局域网上的其他用户在QQ、MSN上发送和接收什么内容;

  3. 局域网上的用户网络游戏的游戏信息;

  4. 没有加密的银行卡账户、密码等。