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



## Oliver_FF (Jun 1, 2008)

*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 



*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++

```
thisSocket = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
```
C#

```
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++

```
int optVal=1;
setsockopt(thisSocket, IPPROTO_IP, 2, (char *)&optVal, sizeof(optVal))
```
C#

```
listeningSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
```

Receiving incoming traffic on all ports
C/C++

```
int inn=1, outt;
long rett;
WSAIoctl(thisSocket, 0x98000001, &inn, sizeof(inn), &outt, sizeof(outt),&rett,0,0)
```
C#

```
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:

```
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 














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.


----------



## Oliver_FF (Jun 1, 2008)

Bump for actually writing the article this time XD


----------



## DrPepper (Jun 1, 2008)

great article it should come in handy one day.


----------



## Kreij (Jun 1, 2008)

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.


----------



## Oliver_FF (Jun 1, 2008)

Kreij said:


> Excellent article.
> 
> I like the interface for your eyeball program too!
> 
> ...



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! 

I blotted the last number in my local address out because (a)nobody needs to know how many computers i've got   (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 (Jun 1, 2008)

I did notice that you used regular button controls in the display area though


----------



## Oliver_FF (Jun 1, 2008)

Kreij said:


> I did notice that you used regular button controls in the display area though



Yeah, take it too far and it just looks tacky  

On a side note, there's over 2,000 lines of code in the C# version  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 (Jun 1, 2008)

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;

```
[color=blue]using[/color] System.Net.Sockets;
....
[color=teal]Socket[/color] mySocket;
```

or call it the long way ..

```
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


----------



## Oliver_FF (Jun 1, 2008)

haha ok, good call


----------



## Phyre (Jun 2, 2008)

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 (Jun 2, 2008)

Phyre said:


> 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:

```
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


----------



## Oliver_FF (Jun 2, 2008)

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 (Dec 14, 2008)

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*

```
/**************************************************************************
****                 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*

```
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*

```
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*

```
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 (Apr 13, 2009)

*Code*

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

Thanks,
Ken


----------



## FordGT90Concept (Apr 13, 2009)

Also, is there a way to drop a packet if it meets certain criteria (act like a firewall, in other words)?


----------



## tradingtrix (Dec 5, 2009)

*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 (Dec 6, 2009)

FordGT90Concept said:


> 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 (Dec 8, 2009)

*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 (Dec 23, 2009)

Oliver_FF said:


> 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 
Thx


----------



## Kreij (Dec 23, 2009)

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 (Dec 23, 2009)

Aren't Raw Sockets removed from WinXP and up? 

Anyways +1 good article.


----------



## Oliver_FF (Jan 1, 2010)

> 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).




YinYang.ERROR said:


> 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 (Jan 22, 2010)

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.


----------



## wrathchild_67 (Jan 24, 2010)

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 (Jan 24, 2010)

xlink said:


> 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.

```
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;

                }



            }
```


----------



## wrathchild_67 (Jan 25, 2010)

Thanks for the reply. Although I did some more research and it looks like performance counters are actually what I need to do after all. The examples I had found up until this point all showed performance counters that were global for a specific NIC, and I thought that was the only way to use the network performance counters. Apparently you can also set performance counters based on PID as well, which is perfect for my needs.


----------



## xlink (Jan 31, 2010)

thanks for the tip Oliver, if you would be kind enough to go through my other question I would greatly appreciate it -> http://forums.techpowerup.com/showthread.php?t=114182


----------

