Показать сообщение отдельно

  #2  
Старый 11.06.2008, 15:48
Delimiter
Banned
Регистрация: 08.04.2005
Сообщений: 446
Провел на форуме:
2187381

Репутация: 518
По умолчанию

Код:
#include <conio.h>
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")

#define MAX_PACKET_SIZE    0x10000
#define SIO_RCVALL         0x98000001
// Буфер для приёма данных
char Buffer[MAX_PACKET_SIZE]; // 64 Kb

//Структура заголовка IP-пакета

typedef struct IPHeader {
  UCHAR   iph_verlen;   // версия и длина заголовка
  UCHAR   iph_tos;      // тип сервиса
  USHORT  iph_length;   // длина всего пакета
  USHORT  iph_id;       // Идентификация
  USHORT  iph_offset;   // флаги и смещения
  UCHAR   iph_ttl;      // время жизни пакета
  UCHAR   iph_protocol; // протокол
  USHORT  iph_xsum;     // контрольная сумма
  ULONG   iph_src;      // IP-адрес отправителя
  ULONG   iph_dest;     // IP-адрес назначения
} IPHeader;

char src[10];
char dest[10];
char ds[15];
unsigned short lowbyte;
unsigned short hibyte;


 void mytransstr( char *buf,int len,char *dst)
 {
   int i,k=0;
   char prstr[10];
   char tstr[10];
   char pstr[40];
   char dstr[40];
   unsigned long m;
   strcpy(dst,"");
   strcpy(pstr,"");
   for(i=0,k=0;i<len;i++)
   {
	   if(*((unsigned char *)(buf+i))<16)
	   {
		   strcpy(prstr,"0");
		   strcat(pstr,".");
	   }
	   else
	   {
		   strcpy(prstr,"");
		   sprintf(dstr,"%c",*((unsigned char *)(buf+i)));
		   strcat(pstr,dstr);
	   }
       m=(long )*((unsigned char *)(buf+i));
	   ultoa(m,tstr,16);
       strcat(prstr,tstr);
	   strcat(dst,prstr);
	   strcat(dst," ");
	   if(k>14)
	   {
		   strcat(dst,"\t| ");
		   strcat(dst,pstr);
		   strcpy(pstr,"");
		   strcat(dst,"\r\n");
		   k=0;
	   }
	   else
		   k++;


   }
   strcat(dst,"\t| ");
   strcat(dst,pstr);
   strcat(dst,"\r\n");
   strupr(dst);
 }



void main()
{
  WSADATA     wsadata;   // Инициализация WinSock.
  SOCKET      s;         // Cлущающий сокет.
  char        name[128]; // Имя хоста (компьютера).
  HOSTENT*    phe;       // Информация о хосте.
  SOCKADDR_IN sa;        // Адрес хоста
  IN_ADDR sa1;        //
  unsigned long        flag = 1;  // Флаг PROMISC Вкл/выкл.
  char *place_for; // added !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  // инициализация
  WSAStartup(MAKEWORD(2,2), &wsadata);
  s = socket( PF_INET, SOCK_RAW, 0 );
  gethostname(name, sizeof(name));
  phe = gethostbyname( name );
  ZeroMemory( &sa, sizeof(sa) );
  sa.sin_family = AF_INET;
  sa.sin_addr.s_addr = ((struct in_addr *)phe->h_addr_list[0])->s_addr;
  bind(s, (SOCKADDR *)&sa, sizeof(SOCKADDR));
  
  // Включение promiscuous mode.
  ioctlsocket(s, SIO_RCVALL, &flag);

  // Бесконечный цикл приёма IP-пакетов.
  while( !_kbhit() )
  {
    int count;
    count = recv( s, Buffer, sizeof(Buffer), 0 );
    // обработка IP-пакета
    if( count >= sizeof(IPHeader) )
    {
      place_for=new char[count*3]; // added !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      IPHeader* hdr = (IPHeader *)Buffer;
      //Начинаем разбор пакета...
      
	strcpy(src,"Пакет: ");
	CharToOem(src,dest);
	printf(dest);
	// Преобразуем в понятный вид адрес отправителя.
	printf("From ");
	sa1.s_addr = hdr->iph_src;
	printf(inet_ntoa(sa1));

	// Преобразуем в понятный вид адрес получателя.
	printf(" To ");
	sa1.s_addr = hdr->iph_dest;
	printf(inet_ntoa(sa1));

	// Вычисляем протокол. Полный список этих констант
	// содержится в файле winsock2.h
	printf(" Prot: ");
	if(hdr->iph_protocol == IPPROTO_TCP) printf("TCP ");
	if(hdr->iph_protocol == IPPROTO_UDP) printf("UDP ");
	if(hdr->iph_protocol == IPPROTO_IP) printf("IP ");
	if(hdr->iph_protocol == IPPROTO_ICMP) printf("ICMP ");
	if(hdr->iph_protocol == IPPROTO_IGMP) printf("IGMP ");
	if(hdr->iph_protocol == IPPROTO_GGP) printf("GGP ");
	if(hdr->iph_protocol == IPPROTO_PUP) printf("PUP ");
	if(hdr->iph_protocol == IPPROTO_IDP) printf("IDP ");
	if(hdr->iph_protocol == IPPROTO_ND) printf("ND ");
	if(hdr->iph_protocol == IPPROTO_ICLFXBM) printf("ICLFXBM"); 
    if(hdr->iph_protocol == IPPROTO_ICMPV6) printf("ICMPV6");
	if(hdr->iph_protocol == IPPROTO_IPV6) printf("IPv6");
	if(hdr->iph_protocol == IPPROTO_RAW) printf("RAW ");
	if(hdr->iph_protocol == IPPROTO_MAX) printf("MAX ");
	

	

	// Вычисляем размер. Так как в сети принят прямой порядок
	// байтов, а не обратный, то прийдётся поменять байты местами.
	printf("Size: ");
	lowbyte = hdr->iph_length>>8;
	hibyte = hdr->iph_length<<8;
	hibyte = hibyte + lowbyte;
	//printf("%s",itoa(hibyte,ds,10));
	printf("%u", hibyte);

	// Вычисляем время жизни пакета.
	printf(" TTL:%s",itoa(hdr->iph_ttl,ds,10));
	printf("\n");
        // added !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        mytransstr( Buffer,count,place_for); // дать весь 
        printf("%s\r\n",place_for);                // дамп включая
                                                                 // заголовок IP
              
        delete[] place_for;
    }
  }

  closesocket( s );
  WSACleanup();
}

Последний раз редактировалось Delimiter; 11.06.2008 в 15:55..
 
Ответить с цитированием