Hi there,
well, i have homework of packet sniffing software
i'm not suppose to write the code,but i need to make a report of an existing code and explain it in details.
I found the following code somewhere(the code should be of a packet sniffer) ,but i couldn't run it.I tried over and over and get no result

I used microsoft c++ 2008 to run it in windows platform.

Can anybody tell me why i couldn't run the code?

// File.cpp
#include "header.h"
#include <iostream>
using namespace std;


/* open raw socket, set promiscuous mode */
void init_net() {

	WSADATA w;
	SOCKADDR_IN sa;
	DWORD bytes;
	char hostname[HOSTNAME_LEN];
	struct hostent *h;
	unsigned int opt = 1;

	if (WSAStartup(MAKEWORD(2,2), &w) != 0)
		die("WSAStartup failed\n");

	if ((s0k = socket(AF_INET, SOCK_RAW, IPPROTO_IP)) == INVALID_SOCKET)
		die("unable to open raw socket\n");

	// use default interface
	if ((gethostname(hostname, HOSTNAME_LEN)) == SOCKET_ERROR)
		die("unable to gethostname\n");

	if ((h = gethostbyname(hostname)) == NULL)
		die("unable to gethostbyname\n");

	sa.sin_family = AF_INET;
	sa.sin_port = htons(6000);
	memcpy(&sa.sin_addr.S_un.S_addr, h->h_addr_list[0], h->h_length);

	if ((bind(s0k, (SOCKADDR *)&sa, sizeof(sa))) == SOCKET_ERROR)
		die("unable to bind() socket\n");

	if (promiscuous)	/* -d on the command line to disable promiscuous mode */
		if ((WSAIoctl(s0k, SIO_RCVALL, &opt, sizeof(opt), NULL, 0, &bytes, NULL, NULL)) == SOCKET_ERROR)
			die("failed to set promiscuous mode\n");
}



void main() {

	char pak[PAKSIZE];
	DWORD bytes;
	init_net();

	WriteData( "Program has started: " );
	WriteData( "\r\n\r\n" );
	
	while(1)
	{
		memset(pak, 0, sizeof(pak));
		if ((bytes = recv(s0k, pak, sizeof(pak), 0)) == SOCKET_ERROR)
		{
			die("socket error on recv\n");
		}else{
			process_pak(pak, bytes);
		}
	}
}



void WriteData( const char* buffer ) 
{
	FILE * pFile;
	pFile = fopen( "./File1.txt", "a" );
	printf( buffer );
	fprintf( pFile, buffer );
	fclose( pFile );
}


/* parse pak, print out requested fields */
void process_pak(char *pak, int len) {

	struct iphdr *ip;
	struct tcphdr *tcp;
	char *data;
	unsigned char proto;	/* to avoid repeated dereferencing */
	int i, j, k, end, datasize;

	ip = (struct iphdr *) pak;
	proto = ip->proto;

	printf("Prototype: %i\n", (unsigned char)proto);

	if(proto == IPPROTO_TCP)
	{
		tcp = (struct tcphdr *) (pak + (ip->ihl * 4));

		data = pak + (ip->ihl * 4) + (tcp->tcphl * 4);
		datasize = ntohs(ip->totlen) - (ip->ihl*4) - (tcp->tcphl*4);

/* ==================================== */
/*       START CONTROLE FUNCTIE         */
/* ==================================== */

		i = 0;
		// If the packet size is smaller than the required size, just trow it away!
//		if( datasize < minSize )
//		{
//			return;
//		}

		char temp[50];
		sprintf(temp, "New Package: %x %x %x %x", data[0], data[1], data[2], data[3]);
		WriteData( temp );
		WriteData("\r\n");

		printf("DataSize: %i\r\n", datasize);

		// Print all data to the file.
		for(j=0; j<datasize; j++)
		{
			char temp [10];
			sprintf(temp, "%4i", data[j]);

			WriteData( temp );
			i = (i+1);
			if(i==4){ WriteData("  "); }
			if(i==8) { WriteData("    "); }
			if(i==12){ WriteData("  "); }
			if(i==16) {
				WriteData("     ->     ");
				i=0;
				for(k=(j-15); k<(j+1); k++)
				{
					char temp [10];
					sprintf(temp, "%1c", data[k]);
					if(data[k] < 32)
					{
						sprintf(temp, "%1c", '.');
					}

					WriteData( temp );
					i = (i+1);
					if(i==8) { WriteData("  "); }
				}
				WriteData("\r\n"); i=0;
			}
		}
		if(i > 0)

		WriteData("\r\n");
		WriteData("\r\n");

	}else{
		// No TCP protocol: return and don't waist any time!
		return;
}	}



void bind_to_interface(int choice) {

	SOCKET sd;
	sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
	if (sd == SOCKET_ERROR)
		printf("error on WSASocket\n");

	INTERFACE_INFO InterfaceList[20];
	unsigned long nBytesReturned;
	if (WSAIoctl(sd, SIO_GET_INTERFACE_LIST, 0, 0, &InterfaceList, sizeof(InterfaceList), &nBytesReturned, 0, 0) == SOCKET_ERROR) {
		printf("error fetching interface list\n");
	}

	int nNumInterfaces = nBytesReturned / sizeof(INTERFACE_INFO);
	if (choice > nNumInterfaces) {
		die("invalid interface selection\n");
	}

	if (choice) {
		// bind to the specified interface and return
        SOCKADDR_IN *pAddress;
        pAddress = (SOCKADDR_IN *) & (InterfaceList[choice-1].iiAddress);
        printf("using interface: %s\n", inet_ntoa(pAddress->sin_addr));

		if ((bind(s0k, (SOCKADDR *)&(InterfaceList[choice-1].iiAddress), sizeof(SOCKADDR_IN))) == SOCKET_ERROR)
			die("unable to bind() socket\n");

		return;
}	}

void die(char *s) {
	WSACleanup();
	WriteData( "%s" );
	exit(-1);
}
// header.h
#pragma com
ment(lib, "ws2_32.lib")

#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <time.h>


/* packet header structures */
#pragma pack(push, 1)
struct iphdr {
	unsigned char ihl:4;
	unsigned char ver:4;

	unsigned char tos;
	unsigned short totlen;
	unsigned short id;
	unsigned short frag_and_flags;
	unsigned char ttl;
	unsigned char proto;
	unsigned short checksum;
	unsigned int src;
	unsigned int dst;
};

struct tcphdr {
	unsigned short sport;
	unsigned short dport;
	unsigned int   seq;
	unsigned int   acknum;
	unsigned char  unused:4;
	unsigned char  tcphl:4;
	unsigned char  Flags;
	unsigned short Windows;
	unsigned short cksum;
	unsigned short UrgPointer;
};

#pragma pack(pop)

#define HOSTNAME_LEN 1024
#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#define PAKSIZE 65536

void init_opt(int, char **);
void init_net(void);
void die(char *);
void process_pak(char *, int);
void bind_to_interface(int);
void WriteData( const char* );

/* G L O B A L S */
SOCKET s0k;
short promiscuous=1;

I don't say i understand the code perfectly,but i need to make sure i can run it before start studying it.


thanks in advance

Recommended Answers

All 8 Replies

The below code compiles.. gives only one warning which I cba to fix.. its basically fopen to fopen_s.. u can fix that easily.. its just a compiler warning though.

// File.cpp
#include "header.h"
#include <iostream>
using namespace std;


/* open raw socket, set promiscuous mode */
void init_net() {

	WSADATA w;
	SOCKADDR_IN sa;
	DWORD bytes;
	char hostname[HOSTNAME_LEN];
	struct hostent *h;
	unsigned int opt = 1;

	if (WSAStartup(MAKEWORD(2,2), &w) != 0)
		die("WSAStartup failed\n");

	if ((s0k = socket(AF_INET, SOCK_RAW, IPPROTO_IP)) == INVALID_SOCKET)
		die("unable to open raw socket\n");

	// use default interface
	if ((gethostname(hostname, HOSTNAME_LEN)) == SOCKET_ERROR)
		die("unable to gethostname\n");

	if ((h = gethostbyname(hostname)) == NULL)
		die("unable to gethostbyname\n");

	sa.sin_family = AF_INET;
	sa.sin_port = htons(6000);
	memcpy(&sa.sin_addr.S_un.S_addr, h->h_addr_list[0], h->h_length);

	if ((bind(s0k, (SOCKADDR *)&sa, sizeof(sa))) == SOCKET_ERROR)
		die("unable to bind() socket\n");

	if (promiscuous)	/* -d on the command line to disable promiscuous mode */
		if ((WSAIoctl(s0k, SIO_RCVALL, &opt, sizeof(opt), NULL, 0, &bytes, NULL, NULL)) == SOCKET_ERROR)
			die("failed to set promiscuous mode\n");
}



int main() {

	char pak[PAKSIZE];
	DWORD bytes;
	init_net();

	WriteData( "Program has started: " );
	WriteData( "\r\n\r\n" );

	while(1)
	{
		memset(pak, 0, sizeof(pak));
		if ((bytes = recv(s0k, pak, sizeof(pak), 0)) == SOCKET_ERROR)
		{
			die("socket error on recv\n");
		}else{
			process_pak(pak, bytes);
		}
	}
}



void WriteData( const char* buffer )
{
	FILE * pFile;
	pFile = fopen( "./File1.txt", "a" );
	printf( buffer );
	fprintf( pFile, buffer );
	fclose( pFile );
}


/* parse pak, print out requested fields */
void process_pak(char *pak, int len) {

	struct iphdr *ip;
	struct tcphdr *tcp;
	char *data;
	unsigned char proto;	/* to avoid repeated dereferencing */
	int i, j, k, end, datasize;

	ip = (struct iphdr *) pak;
	proto = ip->proto;

	printf("Prototype: %i\n", (unsigned char)proto);

	if(proto == IPPROTO_TCP)
	{
		tcp = (struct tcphdr *) (pak + (ip->ihl * 4));

		data = pak + (ip->ihl * 4) + (tcp->tcphl * 4);
		datasize = ntohs(ip->totlen) - (ip->ihl*4) - (tcp->tcphl*4);

/* ==================================== */
/*       START CONTROLE FUNCTIE         */
/* ==================================== */

		i = 0;
		// If the packet size is smaller than the required size, just trow it away!
//		if( datasize < minSize )
//		{
//			return;
//		}

		char temp[50];
		sprintf_s(temp, "New Package: %x %x %x %x", data[0], data[1], data[2], data[3]);
		WriteData( temp );
		WriteData("\r\n");

		printf("DataSize: %i\r\n", datasize);

		// Print all data to the file.
		for(j=0; j<datasize; j++)
		{
			char temp [10];
			sprintf_s(temp, "%4i", data[j]);

			WriteData( temp );
			i = (i+1);
			if(i==4){ WriteData("  "); }
			if(i==8) { WriteData("    "); }
			if(i==12){ WriteData("  "); }
			if(i==16) {
				WriteData("     ->     ");
				i=0;
				for(k=(j-15); k<(j+1); k++)
				{
					char temp [10];
					sprintf_s(temp, "%1c", data[k]);
					if(data[k] < 32)
					{
						sprintf_s(temp, "%1c", '.');
					}

					WriteData( temp );
					i = (i+1);
					if(i==8) { WriteData("  "); }
				}
				WriteData("\r\n"); i=0;
			}
		}
		if(i > 0)

		WriteData("\r\n");
		WriteData("\r\n");

	}else{
		// No TCP protocol: return and don't waist any time!
		return;
}	}



void bind_to_interface(int choice) {

	SOCKET sd;
	sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
	if (sd == SOCKET_ERROR)
		printf("error on WSASocket\n");

	INTERFACE_INFO InterfaceList[20];
	unsigned long nBytesReturned;
	if (WSAIoctl(sd, SIO_GET_INTERFACE_LIST, 0, 0, &InterfaceList, sizeof(InterfaceList), &nBytesReturned, 0, 0) == SOCKET_ERROR) {
		printf("error fetching interface list\n");
	}

	int nNumInterfaces = nBytesReturned / sizeof(INTERFACE_INFO);
	if (choice > nNumInterfaces) {
		die("invalid interface selection\n");
	}

	if (choice) {
		// bind to the specified interface and return
        SOCKADDR_IN *pAddress;
        pAddress = (SOCKADDR_IN *) & (InterfaceList[choice-1].iiAddress);
        printf("using interface: %s\n", inet_ntoa(pAddress->sin_addr));

		if ((bind(s0k, (SOCKADDR *)&(InterfaceList[choice-1].iiAddress), sizeof(SOCKADDR_IN))) == SOCKET_ERROR)
			die("unable to bind() socket\n");

		return;
}	}

void die(char *s) {
	WSACleanup();
	WriteData( "%s" );
	exit(-1);
}
// header.h
#pragma comment(lib, "ws2_32.lib")

#include <winsock2.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <time.h>


/* packet header structures */
#pragma pack(push, 1)
struct iphdr {
	unsigned char ihl:4;
	unsigned char ver:4;

	unsigned char tos;
	unsigned short totlen;
	unsigned short id;
	unsigned short frag_and_flags;
	unsigned char ttl;
	unsigned char proto;
	unsigned short checksum;
	unsigned int src;
	unsigned int dst;
};

struct tcphdr {
	unsigned short sport;
	unsigned short dport;
	unsigned int   seq;
	unsigned int   acknum;
	unsigned char  unused:4;
	unsigned char  tcphl:4;
	unsigned char  Flags;
	unsigned short Windows;
	unsigned short cksum;
	unsigned short UrgPointer;
};

#pragma pack(pop)

#define HOSTNAME_LEN 1024
#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#define PAKSIZE 65536

void init_opt(int, char **);
void init_net(void);
void die(char *);
void process_pak(char *, int);
void bind_to_interface(int);
void WriteData( const char* );

/* G L O B A L S */
SOCKET s0k;
short promiscuous=1;

Can you clarify "get no result"? Were you able to build the executable? If so, did you get any error messages when you ran it? If it doesn't print anything to the console (assuming you're running it in a console window), did it occur to you that it might be running correctly?

Start with main() (at line 45 of the first block of code. After it declares a couple of variables, what does it do next? Skip that for a moment, and what does it do next? How is that next thing implemented? Assuming the code actually runs, are you OK to proceed?

sorry to be late,i have suck internet connection


well,
I ran the code but have other problem,the cmd falshed then have the following written in the output window:

'sniff.exe': Loaded 'C:\Users\DELL\Desktop\sniff\Debug\sniff.exe', Symbols loaded.
'sniff.exe': Loaded 'C:\Windows\System32\ntdll.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\kernel32.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\KernelBase.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\ws2_32.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\msvcrt.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\rpcrt4.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\nsi.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\msvcr100d.dll', Symbols loaded.
'sniff.exe': Loaded 'C:\Windows\System32\mswsock.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\user32.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\gdi32.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\lpk.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\usp10.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\imm32.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\msctf.dll', Cannot find or open the PDB file
'sniff.exe': Loaded 'C:\Windows\System32\WSHTCPIP.DLL', Cannot find or open the PDB file
'sniff.exe': Unloaded 'C:\Windows\System32\WSHTCPIP.DLL'
The program '[408] sniff.exe: Native' has exited with code -1 (0xffffffff).

I think the PDB messages are warnings (about not being able to find debug symbols should you wish to use the debugger to see where the problem is) -- see the second response here for more info.

Other than that, the only actual "error" is that your program exited with code -1, which is exactly what the die() function does. Do you now have a File1.txt file? What messages are in it?

,ù-¨ü„ْ‎ ÷8Œِ
that's what i have in File1.txt

Haha, oops. die() doesn't write its argument into the file! Line 190 should read: WriteData( s ); , not WriteData( "%s" );. Then you might get something useful. Sorry I missed that before! :)

thanks so much raptr dflo
i got something useful,at last!!

how would i run the program in frdora

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.