• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

C/C++/C# Packet Sniffing FAQ and How-To

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
C/C++/C# Packet Sniffing FAQ and How-To Win32

Foreword: The content of this article is intended for educational purposes only. Yes, there are lots of wierd and malicious things possible with raw sockets - any replies about those things will be ignored.


What is packet sniffing?
Well when you have a computer on a network, all network packets received on your computers network card are decoded by several layers in the network stack, which is managed by your OS, before the data contained inside the packet is delivered to the application it was intended for. Eg, take MSN - when you've typed a message and press Enter, several things happen.
1. The application passes the text to the top network stack along with details of where it should be sent.
2. The data gets wrapped in a TCP header containing data on what IP address the target computer has, what port the data is going to and a load of other stuff that guarantees delivery of the data.
3. This data then gets wrapped in an IP header containing yet more information.
4. This then gets wrapped in an Ethernet header containing, yes, more information.
5. The final bundle of information, the Packet, is then sent out to your network, when a (large) sequence of bridges, hubs and routers deliver it to it's destination.
6. At the destination the packet gets unwrapped back up through the network stack (no.2-4) and finally the OS delivers the packet to the intended application.
[joke]So never complain about poor latencies in FPS multiplayer games ever again XD[/jokes]
So packet sniffing is where you can instruct the OS to deliver all incoming packets to your machine to ALSO appear on another port giving you an overview of ALL network traffic hitting your computer. More info about the network stack etc is on wikipedia, I could spend an entire article writing about it and i'm sure you're not that bothered XD
This is the most popular one: http://en.wikipedia.org/wiki/TCP/IP_model



How could that be useful/interesting?
Well it lets you view all incoming data to your machine, everything from the IP header and upwards for every packet. Ever wondered how MSN works? or Firefox? or how the TCP layer works? Have you ever thought to yourself "Now I've blocked application XXX in my firewall... I wonder if it's really stopped it". You can also troubleshoot networking problems because you can view all packets, corrupt packets and all. Well wonder no more :D



Getting Started
This uses Sockets!
I won't bother repeating myself, you can find out how to make and use sockets in C/C++ in my other article here: http://forums.techpowerup.com/showthread.php?t=56901

Creating a raw socket
C/C++
Code:
thisSocket = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
C#
Code:
listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Unspecified);
notice this time that we are not after a TCP connection, we are after a Raw socket.
Next up, bind the socket to your local IP address using port 0.

Setting up the raw socket
So we've got a raw socket, but at the moment it won't do anything for you because at the moment it's pretty much a regular socket on the Windows platform.
Receiving IP headers of incoming packets
C/C++
Code:
int optVal=1;
setsockopt(thisSocket, IPPROTO_IP, 2, (char *)&optVal, sizeof(optVal))
C#
Code:
listeningSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

Receiving incoming traffic on all ports
C/C++
Code:
int inn=1, outt;
long rett;
WSAIoctl(thisSocket, 0x98000001, &inn, sizeof(inn), &outt, sizeof(outt),&rett,0,0)
C#
Code:
byte[] inn = new byte[4] { 1, 0, 0, 0 };
byte[] outt = new byte[4];
listeningSocket.IOControl(IOControlCode.ReceiveAll, inn, outt);

Using the raw socket
Now what? Well, now you start listening on the socket. The next network packet to reach your computer will appear on your socket. From there you have to decode all of the headers to extract the useful information. Wikipedia is your friend on this front - i'll only provide a snippet of code to get you started:
Code:
void printIpPacket(unsigned char *data, int length)
{
	printf("-----------------Packet Begins-----------------\n");
	printf("IP Version: %i, Packet Size: %ibytes, Id: %i\n",
				(data[0]>>4), (data[2]*256)+data[3], (data[4]*256)+data[5]);
	
	printf("Fragment: %i, TTL: %i, HL: %iwds, Protocol: %i\n",
				((int)(data[6]>>4)*256)+data[7], data[8], ((char)(data[0]<<4))>>4, data[9]);
	
	printf("Source: %i.%i.%i.%i, Destination: %i.%i.%i.%i\n",
				data[12], data[13], data[14], data[15],
                data[16], data[17], data[18], data[19]);
	
	//the data inside the packet starts at --> data+(((char)(data[0]<<4))>>2)
            //new data length --> length-(((char)(data[0]<<4))>>2)
            //continue printing the rest of the headers :o	

	printf("\n------------------Packet Ends------------------\n");	
}



So what now?
Well that's up to you. I've written two different sniffers to date, one in C# that covered some really snazzy things. It examined all the packets, put them in order for each connection that was in use and allowed you to browse through the connections at will. You've gotta be careful doing this though because you rapidly run out of free memory - especially if your using a lot of internet when sniffing. I had to implement a kind of garbage collection thing to go around and clean up neglected connections and wipe data to stop the app eating up all of my ram XD Notice how there's all kinds of possibilities for analyzing the data you get :D




I've also written one in pure C which spews out packets on a first-come-first-served basis which provides quite the entertainment, it's kinda like watching an ant farm as packets arrive just before their effects appear in your applications.
Here you can see two packets I just pulled out of my C version. The first is a HTTP response from www.techpowerup.com and the second is one my friends saying "techpowerup roxxors" over MSN haha




Oh, Yes the windows firewall does work, and yes this definitely helped me in my University exams this year. :toast:
 

Attachments

  • sniff.jpg
    sniff.jpg
    106.8 KB · Views: 29,283
  • e1.jpg
    e1.jpg
    45.7 KB · Views: 29,290
  • e2.jpg
    e2.jpg
    59 KB · Views: 29,089
  • e3.jpg
    e3.jpg
    47.3 KB · Views: 29,508
Last edited:

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
Bump for actually writing the article this time XD
 

DrPepper

The Doctor is in the house
Joined
Jan 16, 2008
Messages
7,482 (1.26/day)
Location
Scotland (It rains alot)
System Name Rusky
Processor Intel Core i7 D0 3.8Ghz
Motherboard Asus P6T
Cooling Thermaltake Dark Knight
Memory 12GB Patriot Viper's 1866mhz 9-9-9-24
Video Card(s) GTX470 1280MB
Storage OCZ Summit 60GB + Samsung 1TB + Samsung 2TB
Display(s) Sharp Aquos L32X20E 1920 x 1080
Case Silverstone Raven RV01
Power Supply Corsair 650 Watt
Software Windows 7 x64
Benchmark Scores 3DMark06 - 18064 http://img.techpowerup.org/090720/Capture002.jpg
:toast: great article it should come in handy one day.
 

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
Excellent article.

I like the interface for your eyeball program too!

You didn't have to block out the destination IP address since it's non-routable. ;)
I usually use something in thhe 10.xxx.xxx.xxx address space as it's both non-routable and easier to type. (like, 10.1.1.1)
I guess I'm just lazy about typing 192.168 all the time. :D
 

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
Excellent article.

I like the interface for your eyeball program too!

You didn't have to block out the destination IP address since it's non-routable. ;)
I usually use something in thhe 10.xxx.xxx.xxx address space as it's both non-routable and easier to type. (like, 10.1.1.1)
I guess I'm just lazy about typing 192.168 all the time. :D

Haha to get the interface looking like that, I first drew it using the GIMP, then created separate JPEGs for all the different elements and dropped them onto the windows form in Visual Studio XD Hacked up to the extreme! :rockout:

I blotted the last number in my local address out because (a)nobody needs to know how many computers i've got :eek: (b)If by some obscure bit of bad luck someone got my ip address from the forum they could find my rig on my network, and I've usually got some kind of port open for obscure networking needs ;)
 

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
I did notice that you used regular button controls in the display area though :D
 

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
I did notice that you used regular button controls in the display area though :D

Yeah, take it too far and it just looks tacky :laugh:

On a side note, there's over 2,000 lines of code in the C# version :cool: Only 335 in the C version haha - including dumping packets to file based on their connections...

According to my mate, who is a total MS fanboy, there's some new software out that lets you do what I've done on the main form without having to effectively photoshop it all on...
 

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
One quick suggestion.
When you put in C# code you may want to let people know the namespace that contains the methods you are using.

For instance, to use the Socket method you either need to do;
Code:
[color=blue]using[/color] System.Net.Sockets;
....
[color=teal]Socket[/color] mySocket;

or call it the long way ..
Code:
System.Net.Sockets.[color=teal]Socket[/color] mySocket;

It gives people a little help trying to find the methods in the jillions of MS namespaces :D
 

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
haha ok, good call
 

Phyre

New Member
Joined
Jun 2, 2008
Messages
1 (0.00/day)
Very nice. Got a question though: is it possible to find out what packets are going to and from each process? You say on step 6 that the OS directs the packet to the process.. But is it possible for we, as the programmer, to intercept this and then perhaps filter all the packets so only packets going to and from suchandsucha.exe are shown?
 

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
Very nice. Got a question though: is it possible to find out what packets are going to and from each process? You say on step 6 that the OS directs the packet to the process.. But is it possible for we, as the programmer, to intercept this and then perhaps filter all the packets so only packets going to and from suchandsucha.exe are shown?

Absolutely.

There's a command you can use in Windows command line:
Code:
netstat -b

(and so i'm assuming an API to access it) that tells you what ports are in use by which processes. You just need to extract port numbers out of the raw packets to be able to match them up with the application they're going to.

Eyeball lets you swap between viewing the packets by host or by port - I never bothered getting around to viewing by application, but it's definitely possible.

In fact, the possibilities are pretty much endless :toast:
 

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
Oh, don't forget that you can only view packets that are coming into your computer - no packets going out. Fortunately for us, if it's over a TCP connection you'll still see all of the acknowledgment packets for the data you've sent - so you know when data is leaving your computer.
 

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
I've had some requests for the source code to the C version of my packet sniffer. It should all work, but might not - it's been a while...

main.c
Code:
/**************************************************************************
****                 Eyeball - A packet capturing tool                 ****
****                                By  The Ninj4                      ****
**************************************************************************/

#define __WINDOWS        //   /lib/libws2_32.a
//#define __LINUX        //   -lsocket -lnsl     ??|ifconfig eth0 (-)promisc|??

#include <stdlib.h>
#include <stdio.h>
#ifdef __WINDOWS
#include <winsock2.h>
#endif
#ifdef __LINUX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <unistd.h>
#include <string.h>
#include <time.h>
#include "ippacket.h"

#define BUFFERSIZE 4098

#ifdef __LINUX
	void closesocket(int socket) { close(socket); }
#endif

int main(int argc, char *argv[])
{
	int thisSocket, optVal=1, newData, result, packetCount;
	int inn=1, outt, more=0;
	long rett;
	time_t nowTime;
	struct sockaddr_in destination; 
	unsigned char packetBuffer[BUFFERSIZE];

#ifdef __WINDOWS
	WSADATA wsaData;
#endif
	
	printf("Welcome to Eyeball!");
	//**************************************
	if (argc<=2)
	{
		printf("\nUseage...");
		printf("\ndood [IP-address] [packet-count] (ml) (o)");
        printf("\n--> eyeball ");
        return EXIT_SUCCESS;
	} 
	
#ifdef __WINDOWS
	WSAStartup(0x0202, &wsaData);
#endif
	//**********************************
	thisSocket = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
	if (thisSocket < 0)
	{
		printf("Socket creation FAILED!");
		if (thisSocket) closesocket(thisSocket);
		return 0;
	}  
	printf("Socket created!");
	//**********************************
#ifdef __WINDOWS	
    if(setsockopt(thisSocket, IPPROTO_IP, 2, (char *)&optVal, sizeof(optVal))<0) 
	{
		printf("\nUnable to set socket options!");
		if (thisSocket) closesocket(thisSocket);
		return 0;
	}
	printf("\nOptions set!");
#endif
	//**********************************
	destination.sin_family = AF_PACKET;
	destination.sin_port = 0;
	destination.sin_addr.s_addr = inet_addr(argv[1]);
	if (bind(thisSocket, (struct sockaddr *)&destination, sizeof(destination))<0){
		printf("\nBinding Socket FAILED!\n");
		if (thisSocket) close(thisSocket);
		return 0;
	}
	printf("\nSocket bound to %s!", argv[1]);
	//**********************************
#ifdef __WINDOWS
	if (WSAIoctl(thisSocket, 0x98000001, &inn, sizeof(inn), &outt, sizeof(outt),&rett,0,0)!=0)   
	{
		printf("\nCouldn't set IO control!\n");
        if (thisSocket) closesocket(thisSocket);
		return 0;	
	}
	printf("\nIO controls set!");
#endif
	//**********************************
	if ((argc>=4) && (strcmp(argv[3], "m")==0))
			more=1;
	//**********************************
	result = atoi(argv[2]);
	packetCount=0;
	printf("\nWaiting for %i packets...\n", result);
	while (packetCount<result || result==0)
	{
		newData = recv(thisSocket, packetBuffer, BUFFERSIZE, 0);
		time(&nowTime);
		printf("\n\nPacket %i: at %u\n", packetCount, (unsigned int)nowTime);
		printIpPacket(packetBuffer, newData, more);
		packetCount++;
	}
	//**********************************
	closesocket(thisSocket);
#ifdef __WINDOWS
	system("PAUSE");
#endif
	return 0;
}
ippacket.h
Code:
void printRawData(unsigned char *data, int length, int more)
{
	int i, c=0;
	printf("     -------------Data Begins-------------\n");
	for (i=0; i<length; i++)
	{
		if ((data[i]>30 && data[i]<122) || 
			(((data[i]==10) || (data[i]==13) || (data[i]==123) || (data[i]==125))
            && (more>0)))
		{
			printf("%c", data[i]);
			c+=1;
                }
		else
		{
			printf("[%i]", data[i]);
			c+=3;
			if (data[i]>9) c++;
			if (data[i]>99) c++;
                }
		if (c>=47)
		{
			printf("\n");
			c=0;
                }
       }
}

void writeRawData(unsigned char *data, int length, int type, FILE *file1)
{
	int i, c=0;
	fprintf(file1, "     -------------Data Begins-------------\n");
	for (i=0; i<length; i++)
	{
		if ((data[i]>30 && data[i]<122) || 
			(((data[i]==10) || (data[i]==13) || (data[i]==123) || (data[i]==125))
            && (type>0)))
		{
			fprintf(file1, "%c", data[i]);
			c+=1;

        }
		else
		{
			fprintf(file1, "[%i]", data[i]);
			c+=3;
			if (data[i]>9) c++;
			if (data[i]>99) c++;
        }
		if (c>=47)
		{
			fprintf(file1, "\n");
			c=0;
        }
   }
}

#include "tcppacket.h"
#include "udppacket.h"

void printIpPacket(unsigned char *data, int length, int more)
{
	printf("-----------------Packet Begins-----------------\n");
	printf("IP Version: %i, Packet Size: %ibytes, Id: %i\n",
				(data[0]>>4), (data[2]*256)+data[3], (data[4]*256)+data[5]);
	
	printf("Fragment: %i, TTL: %i, HL: %iwds, Protocol: %i\n",
				((int)(data[6]>>4)*256)+data[7], data[8], ((char)(data[0]<<4))>>4, data[9]);
	
	printf("Source: %i.%i.%i.%i, Destination: %i.%i.%i.%i\n",
				data[12], data[13], data[14], data[15],
                data[16], data[17], data[18], data[19]);
	
	if (data[9]==6)
		printTcpPacket(data+(((char)(data[0]<<4))>>2), length-(((char)(data[0]<<4))>>2), more);
	else if (data[9]==17)
		printUdpPacket(data+(((char)(data[0]<<4))>>2), length-(((char)(data[0]<<4))>>2), more);
	else
		printRawData(data+(((char)(data[0]<<4))>>2), length-(((char)(data[0]<<4))>>2), more);
	printf("\n------------------Packet Ends------------------\n");	
}

/*
void writeIpPacket(unsigned char *data, int length, int type)
{
	FILE *file1;
	char buffer[3];
	char fileName[30];
	int a=0;
	for (a=0; a<30; a++)
		fileName[a] = 0;
	strcat(fileName, "data\\");
    strcat(fileName, itoa(data[12], buffer, 10));
    strcat(fileName, ".");
    strcat(fileName, itoa(data[13], buffer, 10));
    strcat(fileName, ".");
    strcat(fileName, itoa(data[14], buffer, 10));
    strcat(fileName, ".");
    strcat(fileName, itoa(data[15], buffer, 10));
    strcat(fileName, ".txt");
    if((file1 = fopen(fileName, "ab")) == NULL){ 
		printf("\nError opening output file %s", fileName);
		return;
	}
	fprintf(file1, "-----------------Packet Begins-----------------\n");
	fprintf(file1, "IP Version: %i, Packet Size: %ibytes, Id: %i\n",
				(data[0]>>4), (data[2]*256)+data[3], (data[4]*256)+data[5]);
	
	fprintf(file1, "Fragment: %i, TTL: %i, HL: %iwds, Protocol: %i\n",
				((int)(data[6]>>4)*256)+data[7], data[8], ((char)(data[0]<<4))>>4, data[9]);
	
	fprintf(file1, "Source: %i.%i.%i.%i, Destination: %i.%i.%i.%i\n",
				data[12], data[13], data[14], data[15],
                data[16], data[17], data[18], data[19]);
	
	if (data[9]==6)
		writeTcpPacket(data+(((char)(data[0]<<4))>>2), length-(((char)(data[0]<<4))>>2), type, file1);
	else if (data[9]==17)
		writeUdpPacket(data+(((char)(data[0]<<4))>>2), length-(((char)(data[0]<<4))>>2), type, file1);
	else
		writeRawData(data+(((char)(data[0]<<4))>>2), length-(((char)(data[0]<<4))>>2), type, file1);
	fprintf(file1, "\n------------------Packet Ends------------------\n\n");	
	fclose(file1);
}*/
tcppacket.h
Code:
void printTcpPacket(unsigned char *data, int length, int more)
{
	printf("Source Port: %i, Destination Port: %i\n",
				(data[0]*256)+data[1], (data[2]*256)+data[3]);
	
	printf("Sequence: %i, Acknowledgment: %u\n",
				(data[4]*16777216)+(data[5]*65536)+(data[6]*256)+data[7],
                (data[9]*16777216)+(data[9]*65536)+(data[10]*256)+data[11]);
	
	printf("TCPHdr Size: %i, Flags: ", (data[12] >> 4));

	if ((char)(data[13]<<7)>>7) printf("FIN ");
	if ((char)(data[13]<<6)>>7) printf("SYN ");
	if ((char)(data[13]<<5)>>7) printf("RST ");
	if ((char)(data[13]<<4)>>7) printf("PSH ");
	if ((char)(data[13]<<3)>>7) printf("ACK ");
	if ((char)(data[13]<<2)>>7) printf("URG ");
	if ((char)(data[13]<<1)>>7) printf("ECE ");
	if ((char)(data[13]<<0)>>7) printf("CWR ");
	
	printf("\n");
	printRawData(data+(data[12]>>2), length-(data[12]>>2), more);
}


void writeTcpPacket(unsigned char *data, int length, int type, FILE *file1)
{
	fprintf(file1, "Source Port: %i, Destination Port: %i\n",
				(data[0]*256)+data[1], (data[2]*256)+data[3]);
	
	fprintf(file1, "Sequence: %i, Acknowledgment: %u\n",
				(data[4]*16777216)+(data[5]*65536)+(data[6]*256)+data[7],
                (data[9]*16777216)+(data[9]*65536)+(data[10]*256)+data[11]);
	
	fprintf(file1, "TCPHdr Size: %i, Flags: ", (data[12] >> 4));

	if ((char)(data[13]<<7)>>7) fprintf(file1, "FIN ");
	if ((char)(data[13]<<6)>>7) fprintf(file1, "SYN ");
	if ((char)(data[13]<<5)>>7) fprintf(file1, "RST ");
	if ((char)(data[13]<<4)>>7) fprintf(file1, "PSH ");
	if ((char)(data[13]<<3)>>7) fprintf(file1, "ACK ");
	if ((char)(data[13]<<2)>>7) fprintf(file1, "URG ");
	if ((char)(data[13]<<1)>>7) fprintf(file1, "ECE ");
	if ((char)(data[13]<<0)>>7) fprintf(file1, "CWR ");
	
	fprintf(file1, "\n");
	writeRawData(data+(data[12]>>2), length-(data[12]>>2), type, file1);
}
udppacket.h
Code:
void printUdpPacket(unsigned char *data, int length, int more)
{
	printf("Source Port: %i, Destination Port: %i\n",
				(data[0]*256)+data[1], (data[2]*256)+data[3]);
	
	printf("Length: %i, Checksum: %i\n",
				(data[4]*256)+data[5], (data[6]*256)+data[7]);
	
	printRawData(data+8, length-8, more);
}


void writeUdpPacket(unsigned char *data, int length, int type, FILE *file1)
{
	fprintf(file1, "Source Port: %i, Destination Port: %i\n",
				(data[0]*256)+data[1], (data[2]*256)+data[3]);
	
	fprintf(file1, "Length: %i, Checksum: %i\n",
				(data[4]*256)+data[5], (data[6]*256)+data[7]);
	
	writeRawData(data+8, length-8, type, file1);
}
 

Madmax

New Member
Joined
Apr 13, 2009
Messages
1 (0.00/day)
Code

Hi nice article, :respect:
Do you have the code in this article in a zip file? Or wrapped up in a solution?

Thanks,
Ken
 

FordGT90Concept

"I go fast!1!11!1!"
Joined
Oct 13, 2008
Messages
26,259 (4.63/day)
Location
IA, USA
System Name BY-2021
Processor AMD Ryzen 7 5800X (65w eco profile)
Motherboard MSI B550 Gaming Plus
Cooling Scythe Mugen (rev 5)
Memory 2 x Kingston HyperX DDR4-3200 32 GiB
Video Card(s) AMD Radeon RX 7900 XT
Storage Samsung 980 Pro, Seagate Exos X20 TB 7200 RPM
Display(s) Nixeus NX-EDG274K (3840x2160@144 DP) + Samsung SyncMaster 906BW (1440x900@60 HDMI-DVI)
Case Coolermaster HAF 932 w/ USB 3.0 5.25" bay + USB 3.2 (A+C) 3.5" bay
Audio Device(s) Realtek ALC1150, Micca OriGen+
Power Supply Enermax Platimax 850w
Mouse Nixeus REVEL-X
Keyboard Tesoro Excalibur
Software Windows 10 Home 64-bit
Benchmark Scores Faster than the tortoise; slower than the hare.
Also, is there a way to drop a packet if it meets certain criteria (act like a firewall, in other words)?
 

tradingtrix

New Member
Joined
Dec 5, 2009
Messages
2 (0.00/day)
hi oliver..need your help

hi there,

hi pal, need your help regarding sniffer. Can you help ?
Since i m not a hardcore c++ programmer i want the system to sniff the packets coming from particular port(s). The data inside the packet is already compressed using particular utility written in c++ and i hv to capture that data and then write a utility to decompress the packet using the same utility its been compressed in.
If you ever think of helping me i will tell u about the utility.
For an expert like u...its a childs play. i guess.
Bye
Thanks
 

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
Also, is there a way to drop a packet if it meets certain criteria (act like a firewall, in other words)?

Sadly you can't interfere with any data using a raw socket, you can only send and receive packets. You'd need to write a kernel module (for Linux) or a driver (for Windows) that sits somewhere around the network stack monitoring every packet before they get examined and passed around to specific processes.

Sadly, again, for Windows you need to pay Microsoft a large amount of money to get the software to let you write a driver in, say, C#.

On Linux there are loads of free open-source firewalls so I can't imagine you'd want to write another one...
 

tradingtrix

New Member
Joined
Dec 5, 2009
Messages
2 (0.00/day)
hi oliver

Oliver...
i m getting packets on my network and i m suppose to map those packets

Incoming packet at the front end can be interpreted by mapping onto the following structure.
Struct {
char cNetId[2];
short iNoPackets;
CHAR cPackData[512];
} BcastPackData;
whence,
cNetId[2] Identifies the machine
iNoPackets The number of packets that are sequentially packed
cPackData Buffer containing all the packets.
The buffer when mapped to, by the above structure the number of packets in the buffer can be known. The
next task is to segregate the packets and process the individual packets




Map the incoming buffer onto the structure described in section 1.19.3
Check the net id and number of packets from the structure as described in section 1.19.3
Refer to the section 1.19.3 for the components packet in the structure and the diagram in section 1.19.2
Map the individual packets ( 1st packet, 2nd packet, and so on… ) onto the structure
struct {
short iCompLen;
CHAR cCompData[MAX_MESSAGE_SIZE];
}BcastCmpPacket;
N.B. The above structure is currently used to interpret the incoming packets.



can you help me build the utility on above parameters...
i appreciate any help from you pal.

thanks mate
 

michal.hajdus

New Member
Joined
Dec 23, 2009
Messages
1 (0.00/day)
Sadly you can't interfere with any data using a raw socket, you can only send and receive packets. You'd need to write a kernel module (for Linux) or a driver (for Windows) that sits somewhere around the network stack monitoring every packet before they get examined and passed around to specific processes.

Sadly, again, for Windows you need to pay Microsoft a large amount of money to get the software to let you write a driver in, say, C#.

Hi,
You're saying that every firewall soft for Windows needs a new driver, and therefore needs to pay Microsoft for that? Is there no other option to block a TCP packet?
I have a simmilar task, got I given packet and need to modify it. So I either have to pause-change-resume or block-change-resend.
Is there any option? If not I need to reconsider my whole task :p
Thx
 

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
Since Windows 2000 MS has made APIs available for filtering packets.
Google "Windows Filtering Platform"

I think it comes in the Driver Development Kit (which is free)
 

YinYang.ERROR

New Member
Joined
Apr 7, 2009
Messages
463 (0.08/day)
System Name Echelon
Processor Phenom II x3 720 - 4th Core Unlocked
Motherboard Asus M4A785TD-V EVO
Cooling Stock
Memory Adata 4gb ddr3 1600
Video Card(s) Ati HD 5770
Storage 640gb & 250gb SATA
Display(s) MAG CRT 17"
Case CM 690
Audio Device(s) onboard
Power Supply 600w Cooler Master Silent Pro
Software Windows 7 Ultimate x64
Aren't Raw Sockets removed from WinXP and up?

Anyways +1 good article.
 

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
Since Windows 2000 MS has made APIs available for filtering packets.
Google "Windows Filtering Platform"

I think it comes in the Driver Development Kit (which is free)

Bang on. Last time I checked it wasn't free or there was some kind of suspicious subscription or something required (I guess thats to be expected with Windows but I'm a Linux man and don't put up with such things).


Aren't Raw Sockets removed from WinXP and up?

Anyways +1 good article.

Nah, you need admin privileges to use them however. Right click, "Run as administrator" or you can add some metadata somehow to prompt vista to make the UAC dialog appear when you open your app.



As for the programming related questions, sorry I simply don't have the time to write C for people. IMO if you can't program very well in C you shouldn't be messing with raw sockets - learn about objects, functions, structs, unions, malloc/free and THEN learn about networking and raw sockets. You can't jump straight in the deep end of the pool if you don't know how to swim.
 

xlink

New Member
Joined
Jan 22, 2010
Messages
6 (0.00/day)
Can you explain how to receive packets only under a specified port?

I have tried to bind the socket to the specified port : "mainSocket.Bind(new IPEndPoint(IPAddress.Parse(cmbInterfaces.Text), 8687));" but it does not work, it still receives all packets.
 
Joined
Jun 16, 2009
Messages
272 (0.05/day)
Processor Intel Core i7 2500K @ 5GHz 1.4v
Motherboard Asrock Z77E-ITX
Cooling Corsair H60 with 2 x 120mm push/pull exhaust, 140mm intake
Memory 8GB Samsung 30nm DDR3 1600 @ 2133 9-10-10-20-1t 1.45v
Video Card(s) Asus Geforce 480 GTX w/low idle voltage BIOS
Storage 128GB Plextor M3P SSD, 3 x 2TB Hitachi 5400rpm in RAID0
Display(s) 2x eMachines 22" 1080p LCDs
Case Lian Li Q08A Mini-ITX
Audio Device(s) Onboard
Power Supply Corsair AX750 80Plus Gold
Software Windows 7 Ultimate x64
Mediocre C# programmer here. I'm writing a program that will keep a Windows computer from sleeping/standing by when certain applications are running and have network activity. It is similar to the feature in uTorrent that prevents standby when torrents are active, except you can specify a list of programs to monitor. I'm writing this because of a scheduled task I use to put the computer to sleep when it's idle. The Windows power management settings have looser rules on this, so the computer doesn't always go to sleep when following just the power management rules. The problem with the scheduled task is that it seems to override some programs features to prevent the computer from going to sleep, so the computer goes off more often than it should and I have to do a wake on LAN frequently to wake it up.

I'm stumped as to how to detect network traffic from a particular application. I've looked into the IPHelper API and performance counters, but neither seems to offer what I need. I'd really like to avoid using a third party DLL... Any ideas?
 

Oliver_FF

New Member
Joined
Oct 15, 2006
Messages
544 (0.09/day)
Processor Intel q9400 @ stock
Motherboard Lanparty P45-T2RS
Cooling Zalman CNPS-9500
Memory 8GB OCZ PC2-6400
Video Card(s) BFG Nvidia GTX285 OC
Storage 1TB, 500GB, 500GB
Display(s) 20" Samsung T200HD
Case Antec Mini P180
Audio Device(s) Sound Blaster X-Fi Elite Pro
Power Supply 700w Hiper
Software Ubuntu x64 virtualising Vista
Can you explain how to receive packets only under a specified port?

I have tried to bind the socket to the specified port : "mainSocket.Bind(new IPEndPoint(IPAddress.Parse(cmbInterfaces.Text), 8687));" but it does not work, it still receives all packets.

You -have- to bind to port 0, then filter the data packets yourself. Construct the IPv4 packet, look at the protocol number (usually 6 or 17 I think) and decode the rest of the data in the appropriate manner which will most likely be a TCP packet. The TCP packet contains the port number.


Mediocre C# programmer here. I'm writing a program that will keep a Windows computer from sleeping/standing by when certain applications are running and have network activity. It is similar to the feature in uTorrent that prevents standby when torrents are active, except you can specify a list of programs to monitor. I'm writing this because of a scheduled task I use to put the computer to sleep when it's idle. The Windows power management settings have looser rules on this, so the computer doesn't always go to sleep when following just the power management rules. The problem with the scheduled task is that it seems to override some programs features to prevent the computer from going to sleep, so the computer goes off more often than it should and I have to do a wake on LAN frequently to wake it up.

I'm stumped as to how to detect network traffic from a particular application. I've looked into the IPHelper API and performance counters, but neither seems to offer what I need. I'd really like to avoid using a third party DLL... Any ideas?

You can use your system tools to determine which programs are using which network ports. You can then filter all incoming packets by that port as mentioned in my first reply. On Windows, "netstat -bn" should list processes and the corresponding port numbers.

This is a snippet for a C# application I wrote last year which takes a port number and tells you which process was using it. You've gotta be quick mind, sometimes you'll miss it.
Code:
            Process p = new Process();

            p.StartInfo.FileName = "netstat";

            p.StartInfo.Arguments = "-bn";

            p.StartInfo.CreateNoWindow = true;

            p.StartInfo.RedirectStandardOutput = true;

            p.StartInfo.UseShellExecute = false;

            p.Start();

            //p.WaitForExit();

            while (!p.StandardOutput.EndOfStream)

            {

                String line = p.StandardOutput.ReadLine();

                if (line.Contains(tcpPacket.DestinationPort + ""))

                {

                    try

                    {

                        line = p.StandardOutput.ReadLine();

                        program = line.Split('[')[1];

                        program = program.Substring(0, program.Length - 5);

                        if (program.Length > 10) program = program.Substring(0, 10);

                    }

                    catch { } 

                    break;

                }



            }
 
Top