<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Binary Tides &#187; sockets</title>
	<atom:link href="http://www.binarytides.com/blog/category/sockets/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.binarytides.com/blog</link>
	<description></description>
	<lastBuildDate>Sat, 24 Jul 2010 05:31:26 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>TCP Connect Port Scanner Source Code in C with Winsock</title>
		<link>http://www.binarytides.com/blog/tcp-connect-port-scanner-code-in-c-with-winsock/</link>
		<comments>http://www.binarytides.com/blog/tcp-connect-port-scanner-code-in-c-with-winsock/#comments</comments>
		<pubDate>Thu, 30 Apr 2009 10:16:00 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Winsock]]></category>
		<category><![CDATA[sockets]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=52</guid>
		<description><![CDATA[TCP connect() scanning is the most basic form of TCP scanning. The program performs a connect() command on those ports of the target machine which are to be checked. If the port is open then the connect() command will succeed and a connection will be established. If the port is closed the connect() function would [...]]]></description>
			<content:encoded><![CDATA[<p>TCP connect() scanning is the most basic form of TCP scanning. The program performs a connect() command on those ports of the target machine which are to be checked. If the port is open then the connect() command will succeed and a connection will be established. If the port is closed the connect() function would simply timeout in the connection attempt.</p>
<p><span id="more-52"></span></p>
<p>The simple steps would be :<br />
1. Start a loop for the port number range to be scanned.<br />
2. Create a Socket inside the loop.<br />
3. Call the connect function using the socket and the port number to connect to the host.<br />
4. If connect returns SOCKET_ERROR then the connection failed hence port closed, otherwise connection established and port open.</p>
<p>The following code does the same. It should be noted that it scans only TCP ports. For a linux version of the same code view this <a href="http://prasshhant.blogspot.com/2009/04/tcp-connect-port-scanner-with-linux.html">post</a>.</p>
<p><strong>Code</strong> :</p>
<pre class="brush: cpp;">
/*
 TCP Connect portscanner with winsock
*/

#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;
#pragma comment(lib, &quot;ws2_32.lib&quot;); //To link the winsock library  

int main(int argc, char **argv)
{
 WSADATA firstsock;
 SOCKET s;
 struct hostent *host;
 int err,i, startport , endport;
 struct sockaddr_in sa; //this stores the destination address
 char hostname[100];

 strncpy((char *)&amp;sa,&quot;&quot;,sizeof sa);
 sa.sin_family = AF_INET; //this line must be like this coz internet

 //Initialise winsock
 if (WSAStartup(MAKEWORD(2,0),&amp;firstsock) != 0)  //CHECKS FOR WINSOCK VERSION 2.0
 {
  fprintf(stderr,&quot;WSAStartup() failed&quot;); //print formatted data specify stream and options
  exit(EXIT_FAILURE);        //or exit(1);
 } 

 printf(&quot;Enter hostname or ip to scan : &quot;);
 gets(hostname);

 printf(&quot;Enter starting port : &quot;);
 scanf(&quot;%d&quot; , &amp;startport);

 printf(&quot;Enter ending port : &quot;);
 scanf(&quot;%d&quot; , &amp;endport);

 if(isdigit(hostname[0]))
 {
  printf(&quot;Doing inet_addr...&quot;);
  sa.sin_addr.s_addr = inet_addr(hostname); //get ip into s_addr
  printf(&quot;Done\n&quot;);
 }
 else if( (host=gethostbyname(hostname)) != 0)
 {
  printf(&quot;Doing gethostbyname()...&quot;);
  strncpy((char *)&amp;sa.sin_addr , (char *)host-&gt;h_addr_list[0] , sizeof sa.sin_addr);
  printf(&quot;Done\n&quot;);
 }
 else
 {
    printf(&quot;Error resolving hostname&quot;);
       exit(EXIT_FAILURE);
 }

 //Start the portscan loop
 printf(&quot;Starting the scan loop...\n&quot;);
 for(i = startport ; i&lt;= endport ; i++)
 {

  s = socket(AF_INET , SOCK_STREAM , 0); //make net a valid socket handle
  if(s &lt; 0)  //if not a socket
  {
   perror(&quot;\nSocket creation failed&quot;);  // perror function prints an error message to stderr
   exit(EXIT_FAILURE);       //or exit(0);
  }

  sa.sin_port = htons(i);
  //connect to the server with that socket
  err = connect(s , (struct sockaddr *)&amp;sa , sizeof sa);

  if(err == SOCKET_ERROR) //connection not accepted
  {
   printf(&quot;%s %-5d Winsock Error Code : %d\n&quot; , hostname , i , WSAGetLastError());
   fflush(stdout);
  }
  else  //connection accepted
  {
   printf(&quot;%s %-5d accepted            \n&quot; , hostname , i);
   if( shutdown( s ,SD_BOTH ) == SOCKET_ERROR )
   {
    perror(&quot;\nshutdown&quot;);// perror function prints an error message to stderr
    exit(EXIT_FAILURE);
   }
  }
  closesocket(s);   //closes the net socket
 }

 fflush(stdout); //clears the contents of a buffer or flushes a stream
 return(0);
}
</pre>
<p>The above can be compiled with vc++ 6.0 for example. Simply create a project and add this file to the project and click run.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=52&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/tcp-connect-port-scanner-code-in-c-with-winsock/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>TCP Connect Port Scanner with Linux Sockets (BSD)</title>
		<link>http://www.binarytides.com/blog/tcp-connect-port-scanner-with-linux-sockets-bsd/</link>
		<comments>http://www.binarytides.com/blog/tcp-connect-port-scanner-with-linux-sockets-bsd/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 17:24:00 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[sockets]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=51</guid>
		<description><![CDATA[TCP Connect Port Scanner works by trying to establish a connection with every port that is being scanned. If a connectio is established then the port is open otherwise closed.
The steps are simple :

1. Create a socket2. Run a Loop to connect with each port on the remote system ; if connection established then port [...]]]></description>
			<content:encoded><![CDATA[<p>TCP Connect Port Scanner works by trying to establish a connection with every port that is being scanned. If a connectio is established then the port is open otherwise closed.</p>
<p>The steps are simple :</p>
<p><span id="more-51"></span></p>
<p>1. Create a socket<br />2. Run a Loop to connect with each port on the remote system ; if connection established then port open otherwise closed.</p>
<p><b>Code</b> :</p>
<pre class="brush: cpp;">
#include&lt;stdio.h&gt;
#include&lt;sys/socket.h&gt;
#include&lt;netinet/in.h&gt;
#include&lt;errno.h&gt;
#include&lt;netdb.h&gt;
#include&lt;string.h&gt;

int main(int argc , char **argv)
{
 struct hostent *host;
 int err, i , net ,start , end;
 char hostname[100];
 struct sockaddr_in sa;
 //Get the hostname to scan
 printf(&quot;Enter hostname or IP : &quot;);
 gets(hostname);
 //Get start port number
 printf(&quot;\nEnter start port number : &quot;);
 scanf(&quot;%d&quot; , &amp;start);
 //Get end port number
 printf(&quot;\nEnter end port number : &quot;);
 scanf(&quot;%d&quot; , &amp;end);

 //Initialise the sockaddr_in structure
 strncpy((char*)&amp;sa , &quot;&quot; , sizeof sa);
 sa.sin_family = AF_INET;

 if(isdigit(hostname[0]))
 {
  printf(&quot;Doing inet_addr...&quot;);
  sa.sin_addr.s_addr = inet_addr(hostname);
  printf(&quot;Done\n&quot;);
 }
 else if((host = gethostbyname(hostname))!=0)
 {
  printf(&quot;Doing gethostbyname...&quot;);
  strncpy((char*)&amp;sa.sin_addr , (char*)host-&gt;h_addr , sizeof sa.sin_addr);
  printf(&quot;Done\n&quot;);
 }
 else
 {
  herror(hostname);
  exit(2);
 }
 //Start the port scan loop
 printf(&quot;Starting the portscan loop : \n&quot;);
 for(i=start ; i&lt;=end ; i++)
 {
  //Fill in the port number
  sa.sin_port = htons(i);
  //Create a socket of type internet
  net = socket(AF_INET , SOCK_STREAM , 0);
  //Check whether socket created fine or not
  if(net &lt; 0)
  {
   perror(&quot;\nSocket&quot;);
   exit(1);
  }
  //Connect using that socket and sockaddr structure
  err = connect(net , (struct sockaddr*)&amp;sa , sizeof sa);

  if(err&lt;0)
  {
   printf(&quot;%s %-5d %s\r&quot; , hostname , i, strerror(errno));
   fflush(stdout);
  }
  else
  {
   printf(&quot;%s %-5d accepted. \n&quot;,  hostname , i);
   //Now shutdown the read and write operations on this socket
   if(shutdown(net , SHUT_RDWR) &lt; 0)
   {
    //Print error with error message mapped from err_no
    perror(&quot;\nShutdown&quot;);
    exit(1);
   }
  }
  close(net);
 }
 printf(&quot;\r&quot;);
 fflush(stdout);
 return(0);
}
</pre>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=51&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/tcp-connect-port-scanner-with-linux-sockets-bsd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C Packet Sniffer Code with Libpcap and Linux Sockets (BSD)</title>
		<link>http://www.binarytides.com/blog/c-packet-sniffer-code-with-libpcap-and-linux-sockets-bsd/</link>
		<comments>http://www.binarytides.com/blog/c-packet-sniffer-code-with-libpcap-and-linux-sockets-bsd/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 13:51:00 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[sockets]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=49</guid>
		<description><![CDATA[Libpcap is a packe capture library which can be used to sniff packets or network traffic over a network interface. Pcap Documentation gives a description of the methods and data structures available in the libpcap library.

To install libpcap on your linux distro you can either download the source from the website and compile it and [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.tcpdump.org/">Libpcap</a> is a packe capture library which can be used to sniff packets or network traffic over a network interface. <a href="http://www.tcpdump.org/pcap3_man.html">Pcap Documentation</a> gives a description of the methods and data structures available in the libpcap library.</p>
<p><span id="more-49"></span></p>
<p>To install libpcap on your linux distro you can either download the source from the <a href="http://www.tcpdump.org/">website</a> and compile it and install. Or if you are on a distro like ubuntu then it can be installed from synaptic package manager. In the list of packages in Synaptic Package Manager look for 2 packages named as libpcap0.8 and libpcap0.8-dev. Install both of them.</p>
<p>To start with the C program the simple steps would be :</p>
<p>1. Find all available devices &#8211; find_alldevs()</p>
<p>find_alldevs() is the function which can be used to get a list of all available network devices or interfaces present on the machine or which can be opened by pcap_open_live() for sniffing purpose.</p>
<p>The prototype is as :</p>
<p>int pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)</p>
<p>where alldevsp is a pointer to an array of of pcap_if_t structures and errbuf is a character pointer and will contain any error message that occured during the function call.</p>
<p>2. Select a device for sniffing data &#8211; pcap_open_live()</p>
<p>pcap_open_live() is the function to get a packet capture descriptor or a handle to a device which has been opened up for sniffing. The protoype is as :</p>
<p>pcap_t *pcap_open_live(const char *device, int snaplen,int promisc, int to_ms, char *errbuf)</p>
<p>device &#8211; is the name of the device as obtained from the call to pcap_findalldevs.<br />
snaplen &#8211; is the maximum amount of data to be captured. 65536 should be sufficient length.<br />
promisc &#8211; 0 or 1 to indicate whether to open the device in promiscuous mode.<br />
to_ms &#8211; the timeout in milliseconds , 0 for no timeout<br />
errbuf &#8211; buffer to contain any error message</p>
<p>It returns a device handler in the form of the structure pcap_t which can be used by pcap_loop() to capture data from.</p>
<p>3. Start sniffing the device &#8211; pcap_loop()<br />
4. Process the sniffed packet &#8211; user defined callback method</p>
<p><strong>Code</strong> :</p>
<pre class="brush: cpp;">

 /*
 Packet sniffer using libpcap library
*/
#include&lt;pcap.h&gt;
#include&lt;stdio.h&gt;
#include&lt;net/ethernet.h&gt;
#include&lt;netinet/ip_icmp.h&gt; //Provides declarations for icmp header
#include&lt;netinet/udp.h&gt; //Provides declarations for udp header
#include&lt;netinet/tcp.h&gt; //Provides declarations for tcp header
#include&lt;netinet/ip.h&gt; //Provides declarations for ip header

void process_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);
void process_ip_packet(unsigned char* , int);
void print_ip_header(unsigned char* , int);
void print_tcp_header(unsigned char* buffer , int size);
void print_udp_header(unsigned char* , int);

FILE *logfile;
struct sockaddr_in source,dest;

int main()
{
 pcap_if_t alldevsp[100] , *device;
 pcap_t *handle; //Handle of the device that shall be sniffed

 char errbuf[100] , *devname , **devs;
 int count = 1 , n;
 //First get the list of available devices
 printf(&quot;Finding available devices ... &quot;);
 if(pcap_findalldevs(&amp;alldevsp, errbuf))
 {
  printf(&quot;Error finding devices : %s&quot; , errbuf);
  exit(1);
 }
 printf(&quot;Done&quot;);
 //Print the available devices
 printf(&quot;\nAvailable Devices are :\n&quot;);
 device = alldevsp;
 while(device != NULL)
 {
  *(devs + count) = device-&gt;name;
  printf(&quot;%d. %s - %s\n&quot;, count++ , device-&gt;name , device-&gt;description);
  device = device-&gt;next;

 }
 //Ask user which device to sniff
 printf(&quot;Enter the number of the device you want to sniff : &quot;);
 scanf(&quot;%d&quot; , &amp;n);
 devname = *(devs + count - 1);
 //Open the device for sniffing
 printf(&quot;Opening device for sniffing ... &quot;);
 handle = pcap_open_live(&quot;eth0&quot; , 65536 , 1 , 0 , errbuf);
 if (handle == NULL) {
  fprintf(stderr, &quot;Couldn't open device eth0 : %s\n&quot; , errbuf);
  exit(1);
 }
 printf(&quot;Done\n&quot;);

 logfile=fopen(&quot;log.txt&quot;,&quot;w&quot;);
 if(logfile==NULL) printf(&quot;Unable to create file.&quot;);

 //Put the device in sniff loop
 pcap_loop(handle , -1 , process_packet , NULL);
 return 0;
}

void process_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
 int size = header-&gt;len;
 struct ether_header *ethh;
 ethh = (struct ether_header *)packet;
 //Print the ethernet header in the log file

 if(ntohs(ethh-&gt;ether_type) == ETHERTYPE_IP)
 {

  process_ip_packet(packet + sizeof *ethh , size - sizeof ethh);
  printf(&quot;%d&quot; , sizeof *ethh);
  fflush(stdout);
 }
 return 0;
}

void process_ip_packet(unsigned char* buffer, int size)
{
 //Get the IP Header part of this packet
 struct iphdr *iph = (struct iphdr*)buffer;
 switch (iph-&gt;protocol) //Check the Protocol and do accordingly...
 {
  case 1:  //ICMP Protocol
   //PrintIcmpPacket(Buffer,Size);
   break;
  case 2:  //IGMP Protocol
   break;
  case 6:  //TCP Protocol
   print_tcp_packet(buffer , size);
   break;
  case 17: //UDP Protocol
   print_udp_packet(buffer , size);
   break;
  default: //Some Other Protocol like ARP etc.
   break;
 }
}

void print_ip_header(unsigned char* Buffer, int Size)
{
 unsigned short iphdrlen;

 struct iphdr *iph = (struct iphdr *)Buffer;
 iphdrlen =iph-&gt;ihl*4;

 memset(&amp;source, 0, sizeof(source));
 source.sin_addr.s_addr = iph-&gt;saddr;

 memset(&amp;dest, 0, sizeof(dest));
 dest.sin_addr.s_addr = iph-&gt;daddr;

 fprintf(logfile,&quot;\n&quot;);
 fprintf(logfile,&quot;IP Header\n&quot;);
 fprintf(logfile,&quot;   |-IP Version        : %d\n&quot;,(unsigned int)iph-&gt;version);
 fprintf(logfile,&quot;   |-IP Header Length  : %d DWORDS or %d Bytes\n&quot;,(unsigned int)iph-&gt;ihl,((unsigned int)(iph-&gt;ihl))*4);
 fprintf(logfile,&quot;   |-Type Of Service   : %d\n&quot;,(unsigned int)iph-&gt;tos);
 fprintf(logfile,&quot;   |-IP Total Length   : %d  Bytes(Size of Packet)\n&quot;,ntohs(iph-&gt;tot_len));
 fprintf(logfile,&quot;   |-Identification    : %d\n&quot;,ntohs(iph-&gt;id));
 //fprintf(logfile,&quot;   |-Reserved ZERO Field   : %d\n&quot;,(unsigned int)iphdr-&gt;ip_reserved_zero);
 //fprintf(logfile,&quot;   |-Dont Fragment Field   : %d\n&quot;,(unsigned int)iphdr-&gt;ip_dont_fragment);
 //fprintf(logfile,&quot;   |-More Fragment Field   : %d\n&quot;,(unsigned int)iphdr-&gt;ip_more_fragment);
 fprintf(logfile,&quot;   |-TTL      : %d\n&quot;,(unsigned int)iph-&gt;ttl);
 fprintf(logfile,&quot;   |-Protocol : %d\n&quot;,(unsigned int)iph-&gt;protocol);
 fprintf(logfile,&quot;   |-Checksum : %d\n&quot;,ntohs(iph-&gt;check));
 fprintf(logfile,&quot;   |-Source IP        : %s\n&quot;,inet_ntoa(source.sin_addr));
 fprintf(logfile,&quot;   |-Destination IP   : %s\n&quot;,inet_ntoa(dest.sin_addr));
}

void print_tcp_packet(unsigned char* Buffer, int Size)
{
 unsigned short iphdrlen;

 struct iphdr *iph = (struct iphdr *)Buffer;
 iphdrlen = iph-&gt;ihl*4;

 struct tcphdr *tcph=(struct tcphdr*)(Buffer + iphdrlen);

 fprintf(logfile,&quot;\n\n***********************TCP Packet*************************\n&quot;); 

 print_ip_header(Buffer,Size);

 fprintf(logfile,&quot;\n&quot;);
 fprintf(logfile,&quot;TCP Header\n&quot;);
 fprintf(logfile,&quot;   |-Source Port      : %u\n&quot;,ntohs(tcph-&gt;source));
 fprintf(logfile,&quot;   |-Destination Port : %u\n&quot;,ntohs(tcph-&gt;dest));
 fprintf(logfile,&quot;   |-Sequence Number    : %u\n&quot;,ntohl(tcph-&gt;seq));
 fprintf(logfile,&quot;   |-Acknowledge Number : %u\n&quot;,ntohl(tcph-&gt;ack_seq));
 fprintf(logfile,&quot;   |-Header Length      : %d DWORDS or %d BYTES\n&quot; ,(unsigned int)tcph-&gt;doff,(unsigned int)tcph-&gt;doff*4);
 //fprintf(logfile,&quot;   |-CWR Flag : %d\n&quot;,(unsigned int)tcph-&gt;cwr);
 //fprintf(logfile,&quot;   |-ECN Flag : %d\n&quot;,(unsigned int)tcph-&gt;ece);
 fprintf(logfile,&quot;   |-Urgent Flag          : %d\n&quot;,(unsigned int)tcph-&gt;urg);
 fprintf(logfile,&quot;   |-Acknowledgement Flag : %d\n&quot;,(unsigned int)tcph-&gt;ack);
 fprintf(logfile,&quot;   |-Push Flag            : %d\n&quot;,(unsigned int)tcph-&gt;psh);
 fprintf(logfile,&quot;   |-Reset Flag           : %d\n&quot;,(unsigned int)tcph-&gt;rst);
 fprintf(logfile,&quot;   |-Synchronise Flag     : %d\n&quot;,(unsigned int)tcph-&gt;syn);
 fprintf(logfile,&quot;   |-Finish Flag          : %d\n&quot;,(unsigned int)tcph-&gt;fin);
 fprintf(logfile,&quot;   |-Window         : %d\n&quot;,ntohs(tcph-&gt;window));
 fprintf(logfile,&quot;   |-Checksum       : %d\n&quot;,ntohs(tcph-&gt;check));
 fprintf(logfile,&quot;   |-Urgent Pointer : %d\n&quot;,tcph-&gt;urg_ptr);
 fprintf(logfile,&quot;\n&quot;);
 fprintf(logfile,&quot;                        DATA Dump                         &quot;);
 fprintf(logfile,&quot;\n&quot;);

 fprintf(logfile,&quot;IP Header\n&quot;);
 PrintData(Buffer,iphdrlen);

 fprintf(logfile,&quot;TCP Header\n&quot;);
 PrintData(Buffer+iphdrlen,tcph-&gt;doff*4);

 fprintf(logfile,&quot;Data Payload\n&quot;);
 PrintData(Buffer + iphdrlen + tcph-&gt;doff*4 , (Size - tcph-&gt;doff*4-iph-&gt;ihl*4) );

 fprintf(logfile,&quot;\n###########################################################&quot;);
}

void print_udp_packet(unsigned char *Buffer , int Size)
{

 unsigned short iphdrlen;

 struct iphdr *iph = (struct iphdr *)Buffer;
 iphdrlen = iph-&gt;ihl*4;

 struct udphdr *udph = (struct udphdr*)(Buffer + iphdrlen);

 fprintf(logfile,&quot;\n\n***********************UDP Packet*************************\n&quot;);

 print_ip_header(Buffer,Size);   

 fprintf(logfile,&quot;\nUDP Header\n&quot;);
 fprintf(logfile,&quot;   |-Source Port      : %d\n&quot; , ntohs(udph-&gt;source));
 fprintf(logfile,&quot;   |-Destination Port : %d\n&quot; , ntohs(udph-&gt;dest));
 fprintf(logfile,&quot;   |-UDP Length       : %d\n&quot; , ntohs(udph-&gt;len));
 fprintf(logfile,&quot;   |-UDP Checksum     : %d\n&quot; , ntohs(udph-&gt;check));

 fprintf(logfile,&quot;\n&quot;);
 fprintf(logfile,&quot;IP Header\n&quot;);
 PrintData(Buffer , iphdrlen);

 fprintf(logfile,&quot;UDP Header\n&quot;);
 PrintData(Buffer+iphdrlen , sizeof udph);

 fprintf(logfile,&quot;Data Payload\n&quot;);
 PrintData(Buffer + iphdrlen + sizeof udph ,( Size - sizeof udph - iph-&gt;ihl * 4 ));

 fprintf(logfile,&quot;\n###########################################################&quot;);
}

void print_icmp_packet(unsigned char* Buffer , int Size)
{
 unsigned short iphdrlen;

 struct iphdr *iph = (struct iphdr *)Buffer;
 iphdrlen = iph-&gt;ihl*4;

 struct icmphdr *icmph = (struct icmphdr *)(Buffer + iphdrlen);

 fprintf(logfile,&quot;\n\n***********************ICMP Packet*************************\n&quot;); 

 print_ip_header(Buffer , Size);

 fprintf(logfile,&quot;\n&quot;);

 fprintf(logfile,&quot;ICMP Header\n&quot;);
 fprintf(logfile,&quot;   |-Type : %d&quot;,(unsigned int)(icmph-&gt;type));

 if((unsigned int)(icmph-&gt;type) == 11)
  fprintf(logfile,&quot;  (TTL Expired)\n&quot;);
 else if((unsigned int)(icmph-&gt;type) == ICMP_ECHOREPLY)
  fprintf(logfile,&quot;  (ICMP Echo Reply)\n&quot;);
 fprintf(logfile,&quot;   |-Code : %d\n&quot;,(unsigned int)(icmph-&gt;code));
 fprintf(logfile,&quot;   |-Checksum : %d\n&quot;,ntohs(icmph-&gt;checksum));
 //fprintf(logfile,&quot;   |-ID       : %d\n&quot;,ntohs(icmph-&gt;id));
 //fprintf(logfile,&quot;   |-Sequence : %d\n&quot;,ntohs(icmph-&gt;sequence));
 fprintf(logfile,&quot;\n&quot;);

 fprintf(logfile,&quot;IP Header\n&quot;);
 PrintData(Buffer,iphdrlen);

 fprintf(logfile,&quot;UDP Header\n&quot;);
 PrintData(Buffer + iphdrlen , sizeof icmph);

 fprintf(logfile,&quot;Data Payload\n&quot;);
 PrintData(Buffer + iphdrlen + sizeof icmph , (Size - sizeof icmph - iph-&gt;ihl * 4));

 fprintf(logfile,&quot;\n###########################################################&quot;);
}

void PrintData (unsigned char* data , int Size)
{
 int i,j;
 for(i=0 ; i &lt; Size ; i++)
 {
  if( i!=0 &amp;&amp; i%16==0)   //if one line of hex printing is complete...
  {
   fprintf(logfile,&quot;         &quot;);
   for(j=i-16 ; j&lt;i ; j++)
   {
    if(data[j]&gt;=32 &amp;&amp; data[j]&lt;=128)
     fprintf(logfile,&quot;%c&quot;,(unsigned char)data[j]); //if its a number or alphabet

    else fprintf(logfile,&quot;.&quot;); //otherwise print a dot
   }
   fprintf(logfile,&quot;\n&quot;);
  } 

  if(i%16==0) fprintf(logfile,&quot;   &quot;);
  fprintf(logfile,&quot; %02X&quot;,(unsigned int)data[i]);

  if( i==Size-1)  //print the last spaces
  {
   for(j=0;j&lt;15-i%16;j++) fprintf(logfile,&quot;   &quot;); //extra spaces

   fprintf(logfile,&quot;         &quot;);

   for(j=i-i%16 ; j&lt;=i ; j++)
   {
    if(data[j]&gt;=32 &amp;&amp; data[j]&lt;=128) fprintf(logfile,&quot;%c&quot;,(unsigned char)data[j]);
    else fprintf(logfile,&quot;.&quot;);
   }
   fprintf(logfile,&quot;\n&quot;);
  }
 }
}   
</pre>
<p>Compile : gcc sniffer.c -lpcap -o sniffer<br />
Run : sudo ./sniffer</p>
<p>The program requires superuser or root privileges to be able to sniff the packets.<br />
Wireshark(previously ethereal) and tcpdump are examples of applications which use the libpcap library on linux to capture packet data.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=49&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/c-packet-sniffer-code-with-libpcap-and-linux-sockets-bsd/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Packet Sniffer Code in C using Linux Sockets (BSD)</title>
		<link>http://www.binarytides.com/blog/packet-sniffer-code-in-c-using-linux-sockets-bsd/</link>
		<comments>http://www.binarytides.com/blog/packet-sniffer-code-in-c-using-linux-sockets-bsd/#comments</comments>
		<pubDate>Sun, 26 Apr 2009 08:50:00 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[sockets]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=48</guid>
		<description><![CDATA[To code a sniffer in C (Linux) the steps would be :
1. Create a Raw Socket.
2. Put it in a recvfrom loop.
A raw socket when put in recvfrom receives all incoming packets. The following code shows an example of such a sniffer. Note that it sniffs only incoming packets. For sniffing all traffic on a [...]]]></description>
			<content:encoded><![CDATA[<p>To code a sniffer in C (Linux) the steps would be :</p>
<p>1. Create a Raw Socket.<br />
2. Put it in a recvfrom loop.</p>
<p>A raw socket when put in recvfrom receives all incoming packets. The following code shows an example of such a sniffer. Note that it sniffs only incoming packets. For sniffing all traffic on a network a packet capture library like libpcap can be used.</p>
<p><span id="more-48"></span></p>
<p><strong>Code </strong> : sniffer.c</p>
<pre class="brush: cpp;">
#include&lt;netinet/in.h&gt;
#include&lt;errno.h&gt;
#include&lt;netdb.h&gt;
#include&lt;stdio.h&gt;	//For standard things
#include&lt;netinet/ip_icmp.h&gt;	//Provides declarations for icmp header
#include&lt;netinet/udp.h&gt;	//Provides declarations for udp header
#include&lt;netinet/tcp.h&gt;	//Provides declarations for tcp header
#include&lt;netinet/ip.h&gt;	//Provides declarations for ip header
#include&lt;sys/socket.h&gt;
#include&lt;arpa/inet.h&gt;
#include&lt;sys/ioctl.h&gt;
#include&lt;sys/time.h&gt;
#include&lt;sys/types.h&gt;
#include&lt;unistd.h&gt;

void ProcessPacket(unsigned char* , int);
void print_ip_header(unsigned char* , int);
void print_tcp_header(unsigned char* buffer , int size);
void print_udp_header(unsigned char* , int);

int sock_raw;
FILE *logfile;
int tcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;
struct sockaddr_in source,dest;

int main()
{
	int saddr_size , data_size;
	struct sockaddr_in saddr;
	struct in_addr in;

	unsigned char *buffer = (unsigned char *)malloc(65536); //Its Big!

	logfile=fopen(&quot;log.txt&quot;,&quot;w&quot;);
	if(logfile==NULL) printf(&quot;Unable to create file.&quot;);
	printf(&quot;Starting...\n&quot;);
	//Create a raw socket that shall sniff
	sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
	if(sock_raw &lt; 0)
	{
		printf(&quot;Socket Error\n&quot;);
		return 1;
	}
	while(1)
	{
		saddr_size = sizeof saddr;
		//Receive a packet
		data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &amp;saddr , &amp;saddr_size);
		if(data_size &lt;0 )
		{
			printf(&quot;Recvfrom error , failed to get packets\n&quot;);
			return 1;
		}
		//Now process the packet
		ProcessPacket(buffer , data_size);
	}
	close(sock_raw);
	printf(&quot;Finished&quot;);
	return 0;
}

void ProcessPacket(unsigned char* buffer, int size)
{
	//Get the IP Header part of this packet
	struct iphdr *iph = (struct iphdr*)buffer;
	++total;
	switch (iph-&gt;protocol) //Check the Protocol and do accordingly...
	{
		case 1:  //ICMP Protocol
			++icmp;
			//PrintIcmpPacket(Buffer,Size);
			break;

		case 2:  //IGMP Protocol
			++igmp;
			break;

		case 6:  //TCP Protocol
			++tcp;
			print_tcp_packet(buffer , size);
			break;

		case 17: //UDP Protocol
			++udp;
			print_udp_packet(buffer , size);
			break;

		default: //Some Other Protocol like ARP etc.
			++others;
			break;
	}
	printf(&quot;TCP : %d   UDP : %d   ICMP : %d   IGMP : %d   Others : %d   Total : %d\r&quot;,tcp,udp,icmp,igmp,others,total);
}

void print_ip_header(unsigned char* Buffer, int Size)
{
	unsigned short iphdrlen;

	struct iphdr *iph = (struct iphdr *)Buffer;
	iphdrlen =iph-&gt;ihl*4;

	memset(&amp;source, 0, sizeof(source));
	source.sin_addr.s_addr = iph-&gt;saddr;

	memset(&amp;dest, 0, sizeof(dest));
	dest.sin_addr.s_addr = iph-&gt;daddr;

	fprintf(logfile,&quot;\n&quot;);
	fprintf(logfile,&quot;IP Header\n&quot;);
	fprintf(logfile,&quot;   |-IP Version        : %d\n&quot;,(unsigned int)iph-&gt;version);
	fprintf(logfile,&quot;   |-IP Header Length  : %d DWORDS or %d Bytes\n&quot;,(unsigned int)iph-&gt;ihl,((unsigned int)(iph-&gt;ihl))*4);
	fprintf(logfile,&quot;   |-Type Of Service   : %d\n&quot;,(unsigned int)iph-&gt;tos);
	fprintf(logfile,&quot;   |-IP Total Length   : %d  Bytes(Size of Packet)\n&quot;,ntohs(iph-&gt;tot_len));
	fprintf(logfile,&quot;   |-Identification    : %d\n&quot;,ntohs(iph-&gt;id));
	//fprintf(logfile,&quot;   |-Reserved ZERO Field   : %d\n&quot;,(unsigned int)iphdr-&gt;ip_reserved_zero);
	//fprintf(logfile,&quot;   |-Dont Fragment Field   : %d\n&quot;,(unsigned int)iphdr-&gt;ip_dont_fragment);
	//fprintf(logfile,&quot;   |-More Fragment Field   : %d\n&quot;,(unsigned int)iphdr-&gt;ip_more_fragment);
	fprintf(logfile,&quot;   |-TTL      : %d\n&quot;,(unsigned int)iph-&gt;ttl);
	fprintf(logfile,&quot;   |-Protocol : %d\n&quot;,(unsigned int)iph-&gt;protocol);
	fprintf(logfile,&quot;   |-Checksum : %d\n&quot;,ntohs(iph-&gt;check));
	fprintf(logfile,&quot;   |-Source IP        : %s\n&quot;,inet_ntoa(source.sin_addr));
	fprintf(logfile,&quot;   |-Destination IP   : %s\n&quot;,inet_ntoa(dest.sin_addr));
}

void print_tcp_packet(unsigned char* Buffer, int Size)
{
	unsigned short iphdrlen;

	struct iphdr *iph = (struct iphdr *)Buffer;
	iphdrlen = iph-&gt;ihl*4;

	struct tcphdr *tcph=(struct tcphdr*)(Buffer + iphdrlen);

	fprintf(logfile,&quot;\n\n***********************TCP Packet*************************\n&quot;);	

	print_ip_header(Buffer,Size);

	fprintf(logfile,&quot;\n&quot;);
	fprintf(logfile,&quot;TCP Header\n&quot;);
	fprintf(logfile,&quot;   |-Source Port      : %u\n&quot;,ntohs(tcph-&gt;source));
	fprintf(logfile,&quot;   |-Destination Port : %u\n&quot;,ntohs(tcph-&gt;dest));
	fprintf(logfile,&quot;   |-Sequence Number    : %u\n&quot;,ntohl(tcph-&gt;seq));
	fprintf(logfile,&quot;   |-Acknowledge Number : %u\n&quot;,ntohl(tcph-&gt;ack_seq));
	fprintf(logfile,&quot;   |-Header Length      : %d DWORDS or %d BYTES\n&quot; ,(unsigned int)tcph-&gt;doff,(unsigned int)tcph-&gt;doff*4);
	//fprintf(logfile,&quot;   |-CWR Flag : %d\n&quot;,(unsigned int)tcph-&gt;cwr);
	//fprintf(logfile,&quot;   |-ECN Flag : %d\n&quot;,(unsigned int)tcph-&gt;ece);
	fprintf(logfile,&quot;   |-Urgent Flag          : %d\n&quot;,(unsigned int)tcph-&gt;urg);
	fprintf(logfile,&quot;   |-Acknowledgement Flag : %d\n&quot;,(unsigned int)tcph-&gt;ack);
	fprintf(logfile,&quot;   |-Push Flag            : %d\n&quot;,(unsigned int)tcph-&gt;psh);
	fprintf(logfile,&quot;   |-Reset Flag           : %d\n&quot;,(unsigned int)tcph-&gt;rst);
	fprintf(logfile,&quot;   |-Synchronise Flag     : %d\n&quot;,(unsigned int)tcph-&gt;syn);
	fprintf(logfile,&quot;   |-Finish Flag          : %d\n&quot;,(unsigned int)tcph-&gt;fin);
	fprintf(logfile,&quot;   |-Window         : %d\n&quot;,ntohs(tcph-&gt;window));
	fprintf(logfile,&quot;   |-Checksum       : %d\n&quot;,ntohs(tcph-&gt;check));
	fprintf(logfile,&quot;   |-Urgent Pointer : %d\n&quot;,tcph-&gt;urg_ptr);
	fprintf(logfile,&quot;\n&quot;);
	fprintf(logfile,&quot;                        DATA Dump                         &quot;);
	fprintf(logfile,&quot;\n&quot;);

	fprintf(logfile,&quot;IP Header\n&quot;);
	PrintData(Buffer,iphdrlen);

	fprintf(logfile,&quot;TCP Header\n&quot;);
	PrintData(Buffer+iphdrlen,tcph-&gt;doff*4);

	fprintf(logfile,&quot;Data Payload\n&quot;);
	PrintData(Buffer + iphdrlen + tcph-&gt;doff*4 , (Size - tcph-&gt;doff*4-iph-&gt;ihl*4) );

	fprintf(logfile,&quot;\n###########################################################&quot;);
}

void print_udp_packet(unsigned char *Buffer , int Size)
{

	unsigned short iphdrlen;

	struct iphdr *iph = (struct iphdr *)Buffer;
	iphdrlen = iph-&gt;ihl*4;

	struct udphdr *udph = (struct udphdr*)(Buffer + iphdrlen);

	fprintf(logfile,&quot;\n\n***********************UDP Packet*************************\n&quot;);

	print_ip_header(Buffer,Size);			

	fprintf(logfile,&quot;\nUDP Header\n&quot;);
	fprintf(logfile,&quot;   |-Source Port      : %d\n&quot; , ntohs(udph-&gt;source));
	fprintf(logfile,&quot;   |-Destination Port : %d\n&quot; , ntohs(udph-&gt;dest));
	fprintf(logfile,&quot;   |-UDP Length       : %d\n&quot; , ntohs(udph-&gt;len));
	fprintf(logfile,&quot;   |-UDP Checksum     : %d\n&quot; , ntohs(udph-&gt;check));

	fprintf(logfile,&quot;\n&quot;);
	fprintf(logfile,&quot;IP Header\n&quot;);
	PrintData(Buffer , iphdrlen);

	fprintf(logfile,&quot;UDP Header\n&quot;);
	PrintData(Buffer+iphdrlen , sizeof udph);

	fprintf(logfile,&quot;Data Payload\n&quot;);
	PrintData(Buffer + iphdrlen + sizeof udph ,( Size - sizeof udph - iph-&gt;ihl * 4 ));

	fprintf(logfile,&quot;\n###########################################################&quot;);
}

void print_icmp_packet(unsigned char* Buffer , int Size)
{
	unsigned short iphdrlen;

	struct iphdr *iph = (struct iphdr *)Buffer;
	iphdrlen = iph-&gt;ihl*4;

	struct icmphdr *icmph = (struct icmphdr *)(Buffer + iphdrlen);

	fprintf(logfile,&quot;\n\n***********************ICMP Packet*************************\n&quot;);	

	print_ip_header(Buffer , Size);

	fprintf(logfile,&quot;\n&quot;);

	fprintf(logfile,&quot;ICMP Header\n&quot;);
	fprintf(logfile,&quot;   |-Type : %d&quot;,(unsigned int)(icmph-&gt;type));

	if((unsigned int)(icmph-&gt;type) == 11)
		fprintf(logfile,&quot;  (TTL Expired)\n&quot;);
	else if((unsigned int)(icmph-&gt;type) == ICMP_ECHOREPLY)
		fprintf(logfile,&quot;  (ICMP Echo Reply)\n&quot;);
	fprintf(logfile,&quot;   |-Code : %d\n&quot;,(unsigned int)(icmph-&gt;code));
	fprintf(logfile,&quot;   |-Checksum : %d\n&quot;,ntohs(icmph-&gt;checksum));
	//fprintf(logfile,&quot;   |-ID       : %d\n&quot;,ntohs(icmph-&gt;id));
	//fprintf(logfile,&quot;   |-Sequence : %d\n&quot;,ntohs(icmph-&gt;sequence));
	fprintf(logfile,&quot;\n&quot;);

	fprintf(logfile,&quot;IP Header\n&quot;);
	PrintData(Buffer,iphdrlen);

	fprintf(logfile,&quot;UDP Header\n&quot;);
	PrintData(Buffer + iphdrlen , sizeof icmph);

	fprintf(logfile,&quot;Data Payload\n&quot;);
	PrintData(Buffer + iphdrlen + sizeof icmph , (Size - sizeof icmph - iph-&gt;ihl * 4));

	fprintf(logfile,&quot;\n###########################################################&quot;);
}

void PrintData (unsigned char* data , int Size)
{

	for(i=0 ; i &lt; Size ; i++)
	{
		if( i!=0 &amp;&amp; i%16==0)   //if one line of hex printing is complete...
		{
			fprintf(logfile,&quot;         &quot;);
			for(j=i-16 ; j&lt;i ; j++)
			{
				if(data[j]&gt;=32 &amp;&amp; data[j]&lt;=128)
					fprintf(logfile,&quot;%c&quot;,(unsigned char)data[j]); //if its a number or alphabet

				else fprintf(logfile,&quot;.&quot;); //otherwise print a dot
			}
			fprintf(logfile,&quot;\n&quot;);
		} 

		if(i%16==0) fprintf(logfile,&quot;   &quot;);
			fprintf(logfile,&quot; %02X&quot;,(unsigned int)data[i]);

		if( i==Size-1)  //print the last spaces
		{
			for(j=0;j&lt;15-i%16;j++) fprintf(logfile,&quot;   &quot;); //extra spaces

			fprintf(logfile,&quot;         &quot;);

			for(j=i-i%16 ; j&lt;=i ; j++)
			{
				if(data[j]&gt;=32 &amp;&amp; data[j]&lt;=128) fprintf(logfile,&quot;%c&quot;,(unsigned char)data[j]);
				else fprintf(logfile,&quot;.&quot;);
			}
			fprintf(logfile,&quot;\n&quot;);
		}
	}
}
</pre>
<p>Compile : gcc sniffer.c</p>
<p>The program must be run as root user or superuser privileges. e.g. sudo ./a.out in ubuntu<br />
The program creates raw sockets which require root access.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=48&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/packet-sniffer-code-in-c-using-linux-sockets-bsd/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Raw Sockets Using Winsock</title>
		<link>http://www.binarytides.com/blog/raw-sockets-using-winsock/</link>
		<comments>http://www.binarytides.com/blog/raw-sockets-using-winsock/#comments</comments>
		<pubDate>Sun, 18 Mar 2007 14:38:00 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Winsock]]></category>
		<category><![CDATA[sockets]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=5</guid>
		<description><![CDATA[Introduction
Raw sockets, or “Raw Packets”, give you the facility to access the entire contents of a packet or datagram, both for reading and writing purpose. In other words, you can fabricate a whole packet according to your likes and dislikes. For example, a TCP packet would contain an IP header, a TCP header, and then [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p style="text-align: justify;">Raw sockets, or “Raw Packets”, give you the facility to access the entire contents of a packet or datagram, both for reading and writing purpose. In other words, you can fabricate a whole packet according to your likes and dislikes. For example, a TCP packet would contain an IP header, a TCP header, and then the actual data that needs to be transmitted. When working with normal sockets, whatever we send to a socket is actually the data part. In such a scenario, the OS network stack takes the responsibility of adding the header with all fields set to relevant values. When we send the data to a destination, the stack adds the headers and sends the packet, and when we receive some data, then the stack removes the headers and hands out the data to our application. So we are saved from the work of designing the headers. For normal internet applications, there is no need to be concerned about the header operations as they are there for the safe transmission and reception of data, and once the transfer is complete, their need is over and they are dumped. But the story doesn’t end there, there are some people who need raw sockets. Raw sockets are widely used in the field of network security for creating both security and insecurity! In this article, we will take a look at the contents of a general TCPpacket, and try to make a raw packet and transmit it. We shall do this on Windows XP using the VC++ 6.0 compiler. OK, so let’s have a look at the IP and TCP headers.</p>
<p><span id="more-5"></span></p>
<p>RFC 791 gives the structure of an IP header as:</p>
<pre class="brush: cpp;">
0                   1                   2                   3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version|  IHL  |Type of Service|          Total Length         |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|         Identification        |Flags|      Fragment Offset    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Time to Live |    Protocol   |         Header Checksum       |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                       Source Address                          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Destination Address                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Options                    |    Padding    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
</pre>
<p>Next comes the TCP header for transmission using the TCP protocol. RFC 793 gives the structure.</p>
<pre class="brush: cpp;">
0                   1                   2                   3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          Source Port          |       Destination Port        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                        Sequence Number                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Acknowledgment Number                      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  Data |           |U|A|P|R|S|F|                               |
| Offset| Reserved  |R|C|S|S|Y|I|            Window             |
|       |           |G|K|H|T|N|N|                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           Checksum            |         Urgent Pointer        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    Options                    |    Padding    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             data                              |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
</pre>
<p>and at the end is your data, bla bla bla bla bla bla…………………..</p>
<p>———————————————————– &lt;&lt;end of packet</p>
<p>To understand the significance of each field, read up the necessary RFC or some other good TCP/IP tutorial on the net as there are plenty. If you have previous knowledge of socket programming, then the headers are self-explanatory. Now, why is the raw socket feature of importance to network security? Well, one important aspect of network security which needs this feature is scanning. Scanning is of many types. For example, scanning for open ports, scanning the type of OS, scanning for vulnerabilities etc.</p>
<p><strong>Raw Sockets and Windows</strong></p>
<p>First of all, it must be understood very clearly that raw sockets is not a feature of the network API (although it must be present there as an option) but of the OS protocol stack. To implement raw sockets, all we have to do is to inform the OS that the packet buffer we are providing will have the header and so the OS should transmit it as is without “adding any header”; that’s all, nothing more to do. The Unix operating system has raw socket support since ancient times. But the problem is with Windows. None of Windows 95, 98, 98SE supported raw sockets.</p>
<p>Raw sockets became available on Windows from Windows 2000; Windows XP continued this. But suddenly, raw socket support was removed from Windows XP through a patch in SP2. Vista doesn’t have it. A security patch called MS05-019 (<a href="http://support.microsoft.com/kb/897656">http://support.microsoft.com/kb/897656</a>) is what disables raw sockets on XP SP2 and can do the same to even SP1. Probably Windows 2003 SP1 also implements the same the result being the end of raw sockets.</p>
<p>An indepth summary is available at <a href="http://seclists.org/nmap-hackers/2005/0005.html">http://seclists.org/nmap-hackers/2005/0005.html</a>. Windows 95, 98, 98SE do not support raw sockets, but this doesn’t end the story. If you want the facility, then the solution is to use a third party packet driver like Winpcap. Such packet drivers will do your task irrespective of what the OS likes and dislikes. Windows XP and XP SP1 have full raw socket support and so life is easy. So if you want to do raw socketing on Windows, then either use Winpcap or don’t feel desperate to install SP2, or otherwise use Windows 2003 which, as per my knowledge, has raw socket support. <a href="http://technet.microsoft.com/hi-in/library/bb457156%28en-us%29.aspx">http://technet.microsoft.com/hi-in/library/bb457156(en-us).aspx</a> should tell more. So let’s brief up:</p>
<p>1. Windows 95, 98, 98SE, NT4.0 — Only raw ICMP and IGMP with restricted<br />
features.</p>
<p>2. Windows 2000, XP, XP SP1, 2003 — Full raw socket support for both receiving<br />
and sending purposes.</p>
<p>3. Windows XP SP2 — Only raw ICMP, IGMP, and UDP with proper source address<br />
(IP spoofing restricted) can be sent. But, full raw sockets can be received,<br />
which means you can sniff all incoming data and read their headers.</p>
<p>Note : Winsock Ver. &gt;=2.0</p>
<p>So if your system doesn’t support raw sockets, then switch to Linux or use<br />
Winpcap.</p>
<p><strong>The Code</strong></p>
<pre class="brush: cpp;">
SOCKET s;
s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); //Create a RAW socket
int optval=1;
setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *)&amp;optval,
sizeof optval);  //Set it to include the header
</pre>
<p>The last line, setsockopt, tells the OS that the socket s will have the<br />
header included (IP_HDRINCL) at the IP (IPPROTO_IP) level in the data buffer<br />
it sends. IPPROTO_RAW creates an absolutely raw socket, and you have to write<br />
all headers yourself. IPPROTO_UDP, IPROTO_TCP are also available for the<br />
respective types of packets.</p>
<p>Now, we shall need two structures like this:</p>
<pre class="brush: cpp;">
typedef struct ip_hdr
{
unsigned char ip_header_len:4; // 4-bit header length (in 32-bit words)
// normally=5 (Means 20 Bytes may be 24 also)
unsigned char ip_version :4;   // 4-bit IPv4 version
unsigned char ip_tos;          // IP type of service
unsigned short ip_total_length; // Total length
unsigned short ip_id;          // Unique identifier

unsigned char ip_frag_offset :5; // Fragment offset field

unsigned char ip_more_fragment :1;
unsigned char ip_dont_fragment :1;
unsigned char ip_reserved_zero :1;

unsigned char ip_frag_offset1; //fragment offset

unsigned char ip_ttl;          // Time to live
unsigned char ip_protocol;     // Protocol(TCP,UDP etc)
unsigned short ip_checksum;    // IP checksum
unsigned int ip_srcaddr;       // Source address
unsigned int ip_destaddr;      // Source address
} IPV4_HDR, *PIPV4_HDR, FAR * LPIPV4_HDR;

// TCP header
typedef struct tcp_header
{
unsigned short source_port;   // source port
unsigned short dest_port;     // destination port
unsigned int sequence;        // sequence number - 32 bits
unsigned int acknowledge;     // acknowledgement number - 32 bits

unsigned char ns :1;          //Nonce Sum Flag Added in RFC 3540.
unsigned char reserved_part1:3; //according to rfc
unsigned char data_offset:4;    /*The number of 32-bit words
in the TCP header.
This indicates where the data begins.
The length of the TCP header
is always a multiple
of 32 bits.*/

unsigned char fin :1; //Finish Flag
unsigned char syn :1; //Synchronise Flag
unsigned char rst :1; //Reset Flag
unsigned char psh :1; //Push Flag
unsigned char ack :1; //Acknowledgement Flag
unsigned char urg :1; //Urgent Flag

unsigned char ecn :1; //ECN-Echo Flag
unsigned char cwr :1; //Congestion Window Reduced Flag

////////////////////////////////

unsigned short window; // window
unsigned short checksum; // checksum
unsigned short urgent_pointer; // urgent pointer
} TCP_HDR , *PTCP_HDR , FAR * LPTCP_HDR , TCPHeader , TCP_HEADER;
</pre>
<p><strong>Little/Big Endian</strong></p>
<p>Did you notice a difference between the RFC specification and the structures declared above? IP header and version have swapped their positions.The urg, ack, and psh flags of the TCP header are all in reverse order? Mistake? Well, this depends on the byte order that is implemented in the machine architecture. There are two types: Little Endian and Big Endian. In Big Endian, the bytes and bits are arranged in their normal order as we read them, which means the MSB (most significant byte) comes first and the LSB (least significant byte) last. But in Little Endian, the thing is totally<br />
reversed. And it must be remembered that all bits are byte wise reversed, which means they are reversed in groups of 8. That’s the rule for making segments of sizes 3 or 5 etc. If it’s a long or int, then a htons() will do the job. Well, enough said, now let’s make our packet.</p>
<pre class="brush: cpp;">
char packet[65536];   //thats big!
IPV4_HDR *v4hdr=NULL;
TCP_HDR *tcphdr=NULL;

v4hdr = (IPV4_HDR *)packet; //lets point to the ip header portion
v4hdr-&gt;ip_version=4;
v4hdr-&gt;ip_header_len=5;
v4hdr-&gt;ip_tos = 0;
v4hdr-&gt;ip_total_length = htons ( sizeof(IPV4_HDR) + sizeof(TCP_HDR) + payload );
v4hdr-&gt;ip_id = htons(2);
</pre>
<p>&#8230;&#8230;&#8230;&#8230;&#8230;and so on</p>
<pre class="brush: cpp;">
tcphdr = (TCP_HDR *)&amp;buf[sizeof(IPV4_HDR)];
//get the pointer to the tcp header in the packet

tcphdr-&gt;source_port = htons(1234);
tcphdr-&gt;dest_port = htons(50000);

tcphdr-&gt;cwr=0;
tcphdr-&gt;ecn=1;
tcphdr-&gt;urg=0;
tcphdr-&gt;ack=0;
</pre>
<p>&#8230;&#8230;&#8230;&#8230;&#8230;&#8230;and so on</p>
<pre class="brush: cpp;">
// Initialize the TCP payload to some rubbish
data = &amp;buf[sizeof(IPV4_HDR) + sizeof(TCP_HDR)];
memset(data, '^', payload);
</pre>
<p>Get the remote host details in a sockaddr_in dest and call:</p>
<pre class="brush: cpp;">
sendto(s , buf , sizeof(IPV4_HDR)+sizeof(TCP_HDR) +
payload, 0,(SOCKADDR *)&amp;dest, sizeof(dest));
</pre>
<p>where payload is the size of the data after the TCP header. That’s it! We<br />
are done.</p>
<p>To check whether the packets went out as you expected them to, use a<br />
sniffer like Ethereal and sniff them. Note: If you have any firewall running,<br />
then raw packets may be blocked.</p>
<p><span style="font-weight: bold;">Source Code :</span></p>
<pre class="brush: cpp;">
//raw tcp packet crafter

#include &quot;stdio.h&quot;
#include &quot;winsock2.h&quot;
#include &quot;ws2tcpip.h&quot; //IP_HDRINCL is here
#include &quot;conio.h&quot;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //winsock 2.2 library

typedef struct ip_hdr
{
unsigned char ip_header_len:4; // 4-bit header length (in 32-bit words) normally=5 (Means 20 Bytes may be 24 also)
unsigned char ip_version :4; // 4-bit IPv4 version
unsigned char ip_tos; // IP type of service
unsigned short ip_total_length; // Total length
unsigned short ip_id; // Unique identifier

unsigned char ip_frag_offset :5; // Fragment offset field

unsigned char ip_more_fragment :1;
unsigned char ip_dont_fragment :1;
unsigned char ip_reserved_zero :1;

unsigned char ip_frag_offset1; //fragment offset

unsigned char ip_ttl; // Time to live
unsigned char ip_protocol; // Protocol(TCP,UDP etc)
unsigned short ip_checksum; // IP checksum
unsigned int ip_srcaddr; // Source address
unsigned int ip_destaddr; // Source address
} IPV4_HDR, *PIPV4_HDR, FAR * LPIPV4_HDR;

// TCP header
typedef struct tcp_header
{
unsigned short source_port; // source port
unsigned short dest_port; // destination port
unsigned int sequence; // sequence number - 32 bits
unsigned int acknowledge; // acknowledgement number - 32 bits

unsigned char ns :1; //Nonce Sum Flag Added in RFC 3540.
unsigned char reserved_part1:3; //according to rfc
unsigned char data_offset:4; /*The number of 32-bit words in the TCP header.
This indicates where the data begins.
The length of the TCP header is always a multiple
of 32 bits.*/

unsigned char fin :1; //Finish Flag
unsigned char syn :1; //Synchronise Flag
unsigned char rst :1; //Reset Flag
unsigned char psh :1; //Push Flag
unsigned char ack :1; //Acknowledgement Flag
unsigned char urg :1; //Urgent Flag

unsigned char ecn :1; //ECN-Echo Flag
unsigned char cwr :1; //Congestion Window Reduced Flag

////////////////////////////////

unsigned short window; // window
unsigned short checksum; // checksum
unsigned short urgent_pointer; // urgent pointer
} TCP_HDR , *PTCP_HDR , FAR * LPTCP_HDR , TCPHeader , TCP_HEADER;

int main()
{
char host[100],buf[1000],*data=NULL,source_ip[20]; //buf is the complete packet
SOCKET s;
int k=1;

IPV4_HDR *v4hdr=NULL;
TCP_HDR *tcphdr=NULL;

int payload=512 , optval;
SOCKADDR_IN dest;
hostent *server;

//Initialise Winsock
WSADATA wsock;
printf(&quot;\nInitialising Winsock...&quot;);
if (WSAStartup(MAKEWORD(2,2),&amp;wsock) != 0)
{
fprintf(stderr,&quot;WSAStartup() failed&quot;);
exit(EXIT_FAILURE);
}
printf(&quot;Initialised successfully.&quot;);
////////////////////////////////////////////////

//Create Raw TCP Packet
printf(&quot;\nCreating Raw TCP Socket...&quot;);
if((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW))==SOCKET_ERROR)
{
printf(&quot;Creation of raw socket failed.&quot;);
return 0;
}
printf(&quot;Raw TCP Socket Created successfully.&quot;);
////////////////////////////////////////////////

//Put Socket in RAW Mode.
printf(&quot;\nSetting the socket in RAW mode...&quot;);
if(setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *)&amp;optval, sizeof(optval))==SOCKET_ERROR)
{
printf(&quot;failed to set socket in raw mode.&quot;);
return 0;
}
printf(&quot;Successful.&quot;);
////////////////////////////////////////////////

//Target Hostname
printf(&quot;\nEnter hostname : &quot;);
gets(host);
printf(&quot;\nResolving Hostname...&quot;);
if((server=gethostbyname(host))==0)
{
printf(&quot;Unable to resolve.&quot;);
return 0;
}
dest.sin_family = AF_INET;
dest.sin_port = htons(50000); //your destination port
memcpy(&amp;dest.sin_addr.s_addr,server-&gt;h_addr,server-&gt;h_length);
printf(&quot;Resolved.&quot;);
/////////////////////////////////////////////////

printf(&quot;\nEnter Source IP : &quot;);
gets(source_ip);

v4hdr = (IPV4_HDR *)buf; //lets point to the ip header portion
v4hdr-&gt;ip_version=4;
v4hdr-&gt;ip_header_len=5;
v4hdr-&gt;ip_tos = 0;
v4hdr-&gt;ip_total_length = htons ( sizeof(IPV4_HDR) + sizeof(TCP_HDR) + payload );
v4hdr-&gt;ip_id = htons(2);
v4hdr-&gt;ip_frag_offset = 0;
v4hdr-&gt;ip_frag_offset1 = 0;
v4hdr-&gt;ip_reserved_zero = 0;
v4hdr-&gt;ip_dont_fragment = 1;
v4hdr-&gt;ip_more_fragment = 0;
v4hdr-&gt;ip_ttl = 8;
v4hdr-&gt;ip_protocol = IPPROTO_TCP;
v4hdr-&gt;ip_srcaddr = inet_addr(source_ip);
v4hdr-&gt;ip_destaddr = inet_addr(inet_ntoa(dest.sin_addr));
v4hdr-&gt;ip_checksum = 0;

tcphdr = (TCP_HDR *)&amp;buf[sizeof(IPV4_HDR)]; //get the pointer to the tcp header in the packet

tcphdr-&gt;source_port = htons(1234);
tcphdr-&gt;dest_port = htons(50000);

tcphdr-&gt;cwr=0;
tcphdr-&gt;ecn=1;
tcphdr-&gt;urg=0;
tcphdr-&gt;ack=0;
tcphdr-&gt;psh=0;
tcphdr-&gt;rst=1;
tcphdr-&gt;syn=0;
tcphdr-&gt;fin=0;
tcphdr-&gt;ns=1;

tcphdr-&gt;checksum = 0;

// Initialize the TCP payload to some rubbish
data = &amp;buf[sizeof(IPV4_HDR) + sizeof(TCP_HDR)];
memset(data, '^', payload);

printf(&quot;\nSending packet...\n&quot;);

while(!_kbhit())
{
printf(&quot; %d packets send\r&quot;,k++);
if((sendto(s , buf , sizeof(IPV4_HDR)+sizeof(TCP_HDR) + payload, 0,
(SOCKADDR *)&amp;dest, sizeof(dest)))==SOCKET_ERROR)
{

printf(&quot;Error sending Packet : %d&quot;,WSAGetLastError());
break;
}
}

return 0;
}
</pre>
<p>VC++ can be used to compile this code. Simply create a project and put this file in it and click run.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=5&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/raw-sockets-using-winsock/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
