<?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>Socket Programming , Game Programming , PHP , Mysql , Ubuntu etc.</description>
	<lastBuildDate>Thu, 02 Feb 2012 09:31:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Beginners&#8217; guide to socket programming with winsock</title>
		<link>http://www.binarytides.com/blog/beginners-guide-to-socket-programming-with-winsock/</link>
		<comments>http://www.binarytides.com/blog/beginners-guide-to-socket-programming-with-winsock/#comments</comments>
		<pubDate>Mon, 26 Dec 2011 10:10:42 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[winsock]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1304</guid>
		<description><![CDATA[What is this about This is a quick guide/tutorial to learning socket programming in C language on Windows. &#8220;Windows&#8221; because the code snippets shown over here will work only on Windows. The windows api to socket programming is called winsock. Sockets are the fundamental &#8220;things&#8221; behind any kind of network communications done by your computer. For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch [...]]]></description>
			<content:encoded><![CDATA[<h3>What is this about</h3>
<p>This is a quick guide/tutorial to learning socket programming in C language on Windows. &#8220;Windows&#8221; because the code snippets shown over here will work only on Windows. The windows api to socket programming is called winsock.</p>
<p>Sockets are the fundamental &#8220;things&#8221; behind any kind of network communications done by your computer. For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype. Any network communication goes through a socket.</p>
<h3>Before you begin</h3>
<p>This tutorial assumes that you have basic knowledge of C and pointers. Also download Visual C++ 2010 Express Edition.</p>
<h3>Initialising Winsock</h3>
<p>Winsock first needs to be initialiased like this :</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Initialise Winsock
*/

#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.&quot;);

	return 0;
}
</pre>
<p>winsock2.h is the header file to be included for winsock functions. ws2_32.lib is the library file to be linked with the program to be able to use winsock functions.</p>
<p>The WSAStartup function is used to start or initialise winsock library. It takes 2 parameters ; the first one is the version we want to load and second one is a WSADATA structure which will hold additional information after winsock has been loaded.</p>
<p>If any error occurs then the WSAStartup function would return a non zero value and WSAGetLastError can be used to get more information about what error happened.</p>
<p>OK , so next step is to create a socket.</p>
<h3>Creating a socket</h3>
<p>The <code>socket()</code> function is used to create a socket.<br />
Here is a code sample :</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Create a TCP socket
*/

#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;
	SOCKET s;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.\n&quot;);

	if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
	{
		printf(&quot;Could not create socket : %d&quot; , WSAGetLastError());
	}

	printf(&quot;Socket created.\n&quot;);

	return 0;
}
</pre>
<p>Function <code>socket()</code> creates a socket and returns a socket descriptor which can be used in other network commands. The above code will create a socket of :</p>
<p>Address Family : AF_INET (this is IP version 4)<br />
Type : SOCK_STREAM (this means connection oriented TCP protocol)<br />
Protocol : 0 [ or IPPROTO_TCP , IPPROTO_UDP ]</p>
<p>It would be a good idea to read some documentation <a target="_blank" href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms740506(v=vs.85).aspx" >here</a></p>
<p>Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server using this socket. We can connect to www.google.com</p>
<p><strong>Note</strong></p>
<p>Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.</p>
<h3>Connect to a Server</h3>
<p>We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to.</p>
<p>To connect to a remote server we need to do a couple of things. First is create a sockaddr_in structure with proper values filled in. Lets create one for ourselves :</p>
<pre class="brush: cpp; title: Code; notranslate">
struct sockaddr_in server;
</pre>
<p>Have a look at the structures</p>
<pre class="brush: cpp; title: Code; notranslate">
// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

typedef struct in_addr {
  union {
    struct {
      u_char s_b1,s_b2,s_b3,s_b4;
    } S_un_b;
    struct {
      u_short s_w1,s_w2;
    } S_un_w;
    u_long S_addr;
  } S_un;
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};
</pre>
<p>The sockaddr_in has a member called sin_addr of type in_addr which has a s_addr which is nothing but a long. It contains the IP address in long format.</p>
<p>Function <code>inet_addr</code> is a very handy function to convert an IP address to a long format. This is how you do it :</p>
<pre class="brush: cpp; title: Code; notranslate">
server.sin_addr.s_addr = inet_addr(&quot;74.125.235.20&quot;);
</pre>
<p>So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample. A little later on we shall see how to find out the ip address of a given domain name.</p>
<p>The last thing needed is the <code>connect</code> function. It needs a socket and a sockaddr structure to connect to. Here is a code sample.</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Create a TCP socket
*/

#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;
	SOCKET s;
	struct sockaddr_in server;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.\n&quot;);

	//Create a socket
	if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
	{
		printf(&quot;Could not create socket : %d&quot; , WSAGetLastError());
	}

	printf(&quot;Socket created.\n&quot;);

	server.sin_addr.s_addr = inet_addr(&quot;74.125.235.20&quot;);
	server.sin_family = AF_INET;
	server.sin_port = htons( 80 );

	//Connect to remote server
	if (connect(s , (struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;connect error&quot;);
		return 1;
	}

	puts(&quot;Connected&quot;);

	return 0;
}
</pre>
<p>It cannot be any simpler. It creates a socket and then connects. If you run the program it should show Connected.<br />
Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection.</p>
<p>OK , so we are now connected. Lets do the next thing , sending some data to the remote server.</p>
<p><strong>Quick Note</strong></p>
<p>The concept of &#8220;connections&#8221; apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable &#8220;stream&#8221; of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by other data.</p>
<p>Other sockets like UDP , ICMP , ARP dont have a concept of &#8220;connection&#8221;. These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.</p>
<h3>Sending Data</h3>
<p>Function <code>send</code> will simply send data. It needs the socket descriptor , the data to send and its size.<br />
Here is a very simple example of sending some data to google.com ip :</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Create a TCP socket
*/

#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;
	SOCKET s;
	struct sockaddr_in server;
	char *message;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.\n&quot;);

	//Create a socket
	if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
	{
		printf(&quot;Could not create socket : %d&quot; , WSAGetLastError());
	}

	printf(&quot;Socket created.\n&quot;);

	server.sin_addr.s_addr = inet_addr(&quot;74.125.235.20&quot;);
	server.sin_family = AF_INET;
	server.sin_port = htons( 80 );

	//Connect to remote server
	if (connect(s , (struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;connect error&quot;);
		return 1;
	}

	puts(&quot;Connected&quot;);

	//Send some data
	message = &quot;GET / HTTP/1.1\r\n\r\n&quot;;
	if( send(s , message , strlen(message) , 0) &lt; 0)
	{
		puts(&quot;Send failed&quot;);
		return 1;
	}
	puts(&quot;Data Send\n&quot;);

	return 0;
}
</pre>
<p>In the above example , we first connect to an ip address and then send the string message &#8220;GET / HTTP/1.1\r\n\r\n&#8221; to it.<br />
The message is actually a http command to fetch the mainpage of a website.</p>
<p>Now that we have send some data , its time to receive a reply from the server. So lets do it.</p>
<h3>Receiving Data</h3>
<p>Function <code>recv</code> is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Create a TCP socket
*/

#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;
	SOCKET s;
	struct sockaddr_in server;
	char *message , server_reply[2000];
	int recv_size;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.\n&quot;);

	//Create a socket
	if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
	{
		printf(&quot;Could not create socket : %d&quot; , WSAGetLastError());
	}

	printf(&quot;Socket created.\n&quot;);

	server.sin_addr.s_addr = inet_addr(&quot;74.125.235.20&quot;);
	server.sin_family = AF_INET;
	server.sin_port = htons( 80 );

	//Connect to remote server
	if (connect(s , (struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;connect error&quot;);
		return 1;
	}

	puts(&quot;Connected&quot;);

	//Send some data
	message = &quot;GET / HTTP/1.1\r\n\r\n&quot;;
	if( send(s , message , strlen(message) , 0) &lt; 0)
	{
		puts(&quot;Send failed&quot;);
		return 1;
	}
	puts(&quot;Data Send\n&quot;);

	//Receive a reply from the server
	if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR)
	{
		puts(&quot;recv failed&quot;);
	}

	puts(&quot;Reply received\n&quot;);

	//Add a NULL terminating character to make it a proper string before printing
	server_reply[recv_size] = '&#92;&#48;';
	puts(server_reply);

	return 0;
}
</pre>
<p>Here is the output of the above code :</p>
<pre class="brush: bash; title: Code; notranslate">

Initialising Winsock...Initialised.
Socket created.
Connected
Data Send

Reply received

HTTP/1.1 302 Found
Location: http://www.google.co.in/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=7da819edfd7af808:FF=0:TM=1324882923:LM=1324882923:S=PdlMu0TE
E3QKrmdB; expires=Wed, 25-Dec-2013 07:02:03 GMT; path=/; domain=.google.com
Date: Mon, 26 Dec 2011 07:02:03 GMT
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

&lt;HTML&gt;&lt;HEAD&gt;&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html;charset=utf-8&quot;&gt;
&lt;TITLE&gt;302 Moved&lt;/TITLE&gt;&lt;/HEAD&gt;&lt;BODY&gt;
&lt;H1&gt;302 Moved&lt;/H1&gt;
The document has moved
&lt;A HREF=&quot;http://www.google.co.in/&quot;&gt;here&lt;/A&gt;.
&lt;/BODY&gt;&lt;/HTML&gt;

Press any key to continue
</pre>
<p>We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com replied with the content of the page we requested. Quite simple!</p>
<p>Now that we have received our reply, its time to close the socket.</p>
<h3>Close socket</h3>
<p>Function <code>closesocket</code> is used to close the socket. Also WSACleanup must be called to unload the winsock library (ws2_32.dll).</p>
<pre class="brush: cpp; title: Code; notranslate">
closesocket(s);
WSACleanup();
</pre>
<p>Thats it.</p>
<h3>Lets Revise</h3>
<p>So in the above example we learned how to :<br />
1. Create a socket<br />
2. Connect to remote server<br />
3. Send some data<br />
4. Receive a reply</p>
<p>Its useful to know that your web browser also does the same thing when you open www.google.com<br />
This kind of socket activity represents a <strong>CLIENT</Strong>. A client is a system that connects to a remote system to fetch or retrieve data.</p>
<p>The other kind of socket activity is called a <strong>SERVER</strong>. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.</p>
<p>Now its time to do some server tasks using sockets. But before we move ahead there are a few side topics that should be covered just incase you need them.</p>
<h3>Get IP address of a hostname/domain</h3>
<p>When connecting to a remote host , it is necessary to have its IP address. Function <code>gethostbyname</code> is used for this purpose. It takes the domain name as the parameter and returns a structure of type hostent. This structure has the ip information. It is present in <code>netdb.h</code>. Lets have a look at this structure </p>
<pre class="brush: cpp; title: Code; notranslate">
/* Description of data base entry for a single host.  */
struct hostent
{
  char *h_name;			/* Official name of host.  */
  char **h_aliases;		/* Alias list.  */
  int h_addrtype;		/* Host address type.  */
  int h_length;			/* Length of address.  */
  char **h_addr_list;		/* List of addresses from name server.  */
};
</pre>
<p>The <code>h_addr_list</code> has the IP addresses. So now lets have some code to use them.</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Get IP address from domain name
*/

#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;
	char *hostname = &quot;www.google.com&quot;;
	char ip[100];
	struct hostent *he;
	struct in_addr **addr_list;
	int i;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.\n&quot;);

	if ( (he = gethostbyname( hostname ) ) == NULL)
	{
		//gethostbyname failed
		printf(&quot;gethostbyname failed : %d&quot; , WSAGetLastError());
		return 1;
	}

	//Cast the h_addr_list to in_addr , since h_addr_list also has the ip address in long format only
	addr_list = (struct in_addr **) he-&gt;h_addr_list;

	for(i = 0; addr_list[i] != NULL; i++)
	{
		//Return the first one;
		strcpy(ip , inet_ntoa(*addr_list[i]) );
	}

	printf(&quot;%s resolved to : %s\n&quot; , hostname , ip);
	return 0;
	return 0;
}
</pre>
<p>Output of the code would look like :</p>
<pre class="brush: bash; title: Code; notranslate">
www.google.com resolved to : 74.125.235.20
</pre>
<p>So the above code can be used to find the ip address of any domain name. Then the ip address can be used to make a connection using a socket.</p>
<p>Function <code>inet_ntoa</code> will convert an IP address in long format to dotted format. This is just the opposite of <code>inet_addr</code>.</p>
<p>So far we have see some important structures that are used. Lets revise them :</p>
<p>1. <code>sockaddr_in</code> &#8211; Connection information. Used by connect , send , recv etc.<br />
2. <code>in_addr</code> &#8211; Ip address in long format<br />
3. <code>sockaddr</code><br />
4. <code>hostent</code> &#8211; The ip addresses of a hostname. Used by gethostbyname</p>
<h3>Server Concepts</h3>
<p>OK now onto server things. Servers basically do the following :</p>
<p>1. Open a socket<br />
2. Bind to a address(and port).<br />
3. Listen for incoming connections.<br />
4. Accept connections<br />
5. Read/Send</p>
<p>We have already learnt how to open a socket. So the next thing would be to bind it.</p>
<h3>Bind a socket</h3>
<p>Function <code>bind</code> can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.</p>
<p>Lets see a code example :</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Bind socket to port 8888 on localhost
*/

#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;
	SOCKET s;
	struct sockaddr_in server;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.\n&quot;);

	//Create a socket
	if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
	{
		printf(&quot;Could not create socket : %d&quot; , WSAGetLastError());
	}

	printf(&quot;Socket created.\n&quot;);

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons( 8888 );

	//Bind
	if( bind(s ,(struct sockaddr *)&amp;server , sizeof(server)) == SOCKET_ERROR)
	{
		printf(&quot;Bind failed with error code : %d&quot; , WSAGetLastError());
	}

	puts(&quot;Bind done&quot;);

	closesocket(s);

	return 0;
}
</pre>
<p>Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application. </p>
<p>This makes it obvious that you cannot have 2 sockets bound to the same port.</p>
<h3>Listen for connections</h3>
<p>After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function <code>listen</code> is used to put the socket in listening mode. Just add the following line after bind.</p>
<pre class="brush: cpp; title: Code; notranslate">
//Listen
listen(s , 3);
</pre>
<p>Thats all. Now comes the main part of accepting new connections.</p>
<h3>Accept connection</h3>
<p>Function <code>accept</code> is used for this. Here is the code</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Bind socket to port 8888 on localhost
*/

#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;
	SOCKET s , new_socket;
	struct sockaddr_in server , client;
	int c;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.\n&quot;);

	//Create a socket
	if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
	{
		printf(&quot;Could not create socket : %d&quot; , WSAGetLastError());
	}

	printf(&quot;Socket created.\n&quot;);

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons( 8888 );

	//Bind
	if( bind(s ,(struct sockaddr *)&amp;server , sizeof(server)) == SOCKET_ERROR)
	{
		printf(&quot;Bind failed with error code : %d&quot; , WSAGetLastError());
	}

	puts(&quot;Bind done&quot;);

	//Listen to incoming connections
	listen(s , 3);

	//Accept and incoming connection
	puts(&quot;Waiting for incoming connections...&quot;);

	c = sizeof(struct sockaddr_in);
	new_socket = accept(s , (struct sockaddr *)&amp;client, &amp;c);
	if (new_socket == INVALID_SOCKET)
	{
		printf(&quot;accept failed with error code : %d&quot; , WSAGetLastError());
	}

	puts(&quot;Connection accepted&quot;);

	closesocket(s);
	WSACleanup();

	return 0;
}
</pre>
<p><strong>Output</strong></p>
<p>Run the program. It should show</p>
<pre class="brush: bash; title: Code; notranslate">
Initialising Winsock...Initialised.
Socket created.
Bind done
Waiting for incoming connections...
</pre>
<p>So now this program is waiting for incoming connections on port 8888. Dont close this program , keep it running.<br />
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type </p>
<pre class="brush: bash; title: Code; notranslate">
telnet localhost 8888
</pre>
<p>And the server output will show</p>
<pre class="brush: bash; title: Code; notranslate">
Initialising Winsock...Initialised.
Socket created.
Bind done
Waiting for incoming connections...
Connection accepted
Press any key to continue
</pre>
<p>So we can see that the client connected to the server. Try the above process till you get it perfect.</p>
<p><strong>Note</strong></p>
<p>You can get the ip address of client and the port of connection by using the sockaddr_in structure passed to accept function. It is very simple :</p>
<pre class="brush: cpp; title: Code; notranslate">
char *client_ip = inet_ntoa(client.sin_addr);
int client_port = ntohs(client.sin_port);
</pre>
<p>We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client. </p>
<p>Here is an example :</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Bind socket to port 8888 on localhost
*/
#include&lt;io.h&gt;
#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;
	SOCKET s , new_socket;
	struct sockaddr_in server , client;
	int c;
	char *message;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.\n&quot;);

	//Create a socket
	if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
	{
		printf(&quot;Could not create socket : %d&quot; , WSAGetLastError());
	}

	printf(&quot;Socket created.\n&quot;);

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons( 8888 );

	//Bind
	if( bind(s ,(struct sockaddr *)&amp;server , sizeof(server)) == SOCKET_ERROR)
	{
		printf(&quot;Bind failed with error code : %d&quot; , WSAGetLastError());
	}

	puts(&quot;Bind done&quot;);

	//Listen to incoming connections
	listen(s , 3);

	//Accept and incoming connection
	puts(&quot;Waiting for incoming connections...&quot;);

	c = sizeof(struct sockaddr_in);
	new_socket = accept(s , (struct sockaddr *)&amp;client, &amp;c);
	if (new_socket == INVALID_SOCKET)
	{
		printf(&quot;accept failed with error code : %d&quot; , WSAGetLastError());
	}

	puts(&quot;Connection accepted&quot;);

	//Reply to client
	message = &quot;Hello Client , I have received your connection. But I have to go now, bye\n&quot;;
	send(new_socket , message , strlen(message) , 0);

	getchar();

	closesocket(s);
	WSACleanup();

	return 0;
}
</pre>
<p>Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :</p>
<pre class="brush: bash; title: Code; notranslate">
Hello Client , I have received your connection. But I have to go now, bye
</pre>
<p>So the client(telnet) received a reply from server. We had to use a getchar because otherwise the output would scroll out of the client terminal without waiting</p>
<p>We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections. </p>
<p>It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the <code>accept</code> in a loop so that it can receive incoming connections all the time.</p>
<h3>Live Server</h3>
<p>So a live server will be alive for all time. Lets code this up :</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Live Server on port 8888
*/
#include&lt;io.h&gt;
#include&lt;stdio.h&gt;
#include&lt;winsock2.h&gt;

#pragma comment(lib,&quot;ws2_32.lib&quot;) //Winsock Library

int main(int argc , char *argv[])
{
	WSADATA wsa;
	SOCKET s , new_socket;
	struct sockaddr_in server , client;
	int c;
	char *message;

	printf(&quot;\nInitialising Winsock...&quot;);
	if (WSAStartup(MAKEWORD(2,2),&amp;wsa) != 0)
	{
		printf(&quot;Failed. Error Code : %d&quot;,WSAGetLastError());
		return 1;
	}

	printf(&quot;Initialised.\n&quot;);

	//Create a socket
	if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
	{
		printf(&quot;Could not create socket : %d&quot; , WSAGetLastError());
	}

	printf(&quot;Socket created.\n&quot;);

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons( 8888 );

	//Bind
	if( bind(s ,(struct sockaddr *)&amp;server , sizeof(server)) == SOCKET_ERROR)
	{
		printf(&quot;Bind failed with error code : %d&quot; , WSAGetLastError());
		exit(EXIT_FAILURE);
	}

	puts(&quot;Bind done&quot;);

	//Listen to incoming connections
	listen(s , 3);

	//Accept and incoming connection
	puts(&quot;Waiting for incoming connections...&quot;);

	c = sizeof(struct sockaddr_in);

	while( (new_socket = accept(s , (struct sockaddr *)&amp;client, &amp;c)) != INVALID_SOCKET )
	{
		puts(&quot;Connection accepted&quot;);

		//Reply to the client
		message = &quot;Hello Client , I have received your connection. But I have to go now, bye\n&quot;;
		send(new_socket , message , strlen(message) , 0);
	}

	if (new_socket == INVALID_SOCKET)
	{
		printf(&quot;accept failed with error code : %d&quot; , WSAGetLastError());
		return 1;
	}

	closesocket(s);
	WSACleanup();

	return 0;
}
</pre>
<p>We havent done a lot there. Just the accept was put in a loop.</p>
<p>Now run the program in 1 terminal , and open 3 other terminals. From each of the 3 terminal do a telnet to the server port.</p>
<p>Run telnet like this</p>
<pre class="brush: bash; title: Code; notranslate">
C:\&gt;telnet
</pre>
<pre class="brush: bash; title: Code; notranslate">
Welcome to Microsoft Telnet Client
Escape Character is 'CTRL+]'
Microsoft Telnet&gt; open localhost 8888
</pre>
<pre class="brush: bash; title: Code; notranslate">
Hello Client , I have received your connection. But I have to go now, bye
</pre>
<p>And the server terminal would show</p>
<pre class="brush: bash; title: Code; notranslate">
Initialising Winsock...Initialised.
Socket created.
Bind done
Waiting for incoming connections...
Connection accepted
Connection accepted
</pre>
<p>So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program.<br />
All telnet terminals would show &#8220;Connection to host lost.&#8221;<br />
Good so far. But still there is not effective communication between the server and the client.</p>
<p>The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections , and handle multiple connections together.</p>
<h3>Handling Connections</h3>
<p>To handle every connection we need a separate handling code to run along with the main server accepting connections.<br />
One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.</p>
<p>We shall now use threads to create handlers for each connection the server accepts. Lets do it pal.</p>
<pre class="brush: cpp; title: Code; notranslate">
</pre>
<p>Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.</p>
<p>The telnet terminals would show :</p>
<pre class="brush: bash; title: Code; notranslate">
</pre>
<p>This one looks good , but the communication handler is also quite dumb. After the greeting it terminates. It should stay alive and keep communicating with the client.</p>
<p>One way to do this is by making the connection handler wait for some message from a client as long as the client is connected. If the client disconnects , the connection handler ends.</p>
<p>So the connection handler can be rewritten like this :</p>
<pre class="brush: cpp; title: Code; notranslate">
</pre>
<p>The above connection handler takes some input from the client and replies back with the same. Simple! Here is how the telnet output might look</p>
<pre class="brush: bash; title: Code; notranslate">
</pre>
<p>So now we have a server thats communicative. Thats useful now.</p>
<h3>Conclusion</h3>
<p>The winsock api is quite similar to Linux sockets in terms of function name and structures. Few differences exist like :</p>
<p>1. Winsock needs to be initialised with the WSAStartup function. No such thing in linux.</p>
<p>2. Header file names are different. Winsock needs winsock2.h , whereas Linux needs socket.h , apra/inet.h , unistd.h and many others.</p>
<p>3. Winsock function to close a socket is <code>closesocket</code> , whereas on Linux it is <code>close</code>.<br />
On Winsock WSACleanup must also be called to unload the winsock dll.</p>
<p>4. On winsock the error number is fetched by the function <code>WSAGetLastError()</code>. On Linux the errno variable from errno.h file is filled with the error number.</p>
<p>And there are many more differences as we go deep.</p>
<p>By now you must have learned the basics of socket programming in C. You can try out some experiments like writing a chat client or something similar.</p>
<p>If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1304&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/beginners-guide-to-socket-programming-with-winsock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handle multiple socket connections with fd_set and select on Linux</title>
		<link>http://www.binarytides.com/blog/handle-multiple-socket-connections-with-fd_set-and-select-on-linux/</link>
		<comments>http://www.binarytides.com/blog/handle-multiple-socket-connections-with-fd_set-and-select-on-linux/#comments</comments>
		<pubDate>Sun, 25 Dec 2011 14:20:51 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1297</guid>
		<description><![CDATA[When writing server programs using sockets , it becomes necessary to handle multiple connections at a time , since a server needs to serve multiple clients. There are many ways to do so. On linux this can be done in various ways like forking , threading , select method etc. In this tutorial we shall use the select method approach. The select function allows the program to monitor multiple sockets for a certain &#8220;activity&#8221; to [...]]]></description>
			<content:encoded><![CDATA[<p>When writing server programs using sockets , it becomes necessary to handle multiple connections at a time , since a server needs to serve multiple clients.</p>
<p>There are many ways to do so. On linux this can be done in various ways like forking , threading , select method etc.</p>
<p>In this tutorial we shall use the select method approach. The <code>select</code> function allows the program to monitor multiple sockets for a certain &#8220;activity&#8221; to occur. For example if there is some data to be read on one of the sockets select will provide that information.</p>
<p><strong>fd_set</strong></p>
<p>An fd_set is a set of sockets to &#8220;monitor&#8221; for some activity. There are four useful macros : FD_CLR, FD_ISSET, FD_SET, FD_ZERO for dealing with an fd_set.</p>
<p>FD_ZERO &#8211; Clear an fd_set<br />
FD_ISSET &#8211; Check if a descriptor is in an fd_set<br />
FD_SET &#8211; Add a descriptor to an fd_set<br />
FD_CLR &#8211; Remove a descriptor from an fd_set</p>
<pre class="brush: cpp; title: Code; notranslate">
//set of socket descriptors
fd_set readfds;

//socket to set
FD_SET( s , &amp;readfds);
</pre>
<p><strong>select</strong></p>
<p>The select method takes a list of socket for monitoring them. Here is how :</p>
<pre class="brush: cpp; title: Code; notranslate">
activity = select( max_clients , &amp;readfds , NULL , NULL , NULL);
</pre>
<p>The <code>select</code> function blocks , till an activity occurs. For example when a socket is ready to be read , select will return and readfs will have those sockets which are ready to be read.</p>
<p><strong>Code</strong></p>
<pre class="brush: cpp; title: Code; notranslate">
/*
 * @brief
 * manage multiple connections with FD_SET
 *
 * @author Silver Moon
 *
 * */

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;	//strlen
#include &lt;stdlib.h&gt;
#include &lt;errno.h&gt;
#include &lt;unistd.h&gt;	//close
#include &lt;arpa/inet.h&gt;	//close
#include &lt;sys/types.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;netinet/in.h&gt;
#include &lt;sys/time.h&gt;	//FD_SET, FD_ISSET, FD_ZERO macros

#define TRUE   1
#define FALSE  0

int main(int argc , char *argv[])
{
	int opt = TRUE;
	int master_socket , addrlen , new_socket , client_socket[30] , max_clients = 30 , activity, i , valread , s;
	struct sockaddr_in address;

	char buffer[1025];	//data buffer of 1K

	//set of socket descriptors
	fd_set readfds;

	//a message
	char *message = &quot;ECHO Daemon v1.0 \r\n&quot;;

	//initialise all client_socket[] to 0 so not checked
	for (i = 0; i &lt; max_clients; i++)
	{
		client_socket[i] = 0;
	}

	//create a master socket
	if( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0)
	{
		perror(&quot;socket failed&quot;);
		exit(EXIT_FAILURE);
	}

	//set master socket to allow multiple connections , this is just a good habit, it will work without this
	if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&amp;opt, sizeof(opt)) &lt; 0 )
	{
		perror(&quot;setsockopt&quot;);
		exit(EXIT_FAILURE);
	}

	//type of socket created
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = INADDR_ANY;
	address.sin_port = htons( 8888 );

	//bind the socket to localhost port 8888
	if (bind(master_socket, (struct sockaddr *)&amp;address, sizeof(address))&lt;0)
	{
		perror(&quot;bind failed&quot;);
		exit(EXIT_FAILURE);
	}

	//try to specify maximum of 3 pending connections for the master socket
	if (listen(master_socket, 3) &lt; 0)
	{
		perror(&quot;listen&quot;);
		exit(EXIT_FAILURE);
	}

	//accept the incoming connection
	addrlen = sizeof(address);
	puts(&quot;Waiting for connections...&quot;);
	while(TRUE)
	{
		//clear the socket set
		FD_ZERO(&amp;readfds);

		//add master socket to set
		FD_SET(master_socket, &amp;readfds);

		//add child sockets to set
		for ( i = 0 ; i &lt; max_clients ; i++)
		{
			s = client_socket[i];
			if(s &gt; 0)
			{
				FD_SET( s , &amp;readfds);
			}
		}

		//wait for an activity on one of the sockets , timeout is NULL , so wait indefinitely
		activity = select( max_clients + 3 , &amp;readfds , NULL , NULL , NULL);

		if ((activity &lt; 0) &amp;&amp; (errno!=EINTR))
		{
			printf(&quot;select error&quot;);
		}

		//If something happened on the master socket , then its an incoming connection
		if (FD_ISSET(master_socket, &amp;readfds))
		{
			if ((new_socket = accept(master_socket, (struct sockaddr *)&amp;address, (socklen_t*)&amp;addrlen))&lt;0)
			{
				perror(&quot;accept&quot;);
				exit(EXIT_FAILURE);
			}

			//inform user of socket number - used in send and receive commands
			printf(&quot;New connection , socket fd is %d , ip is : %s , port : %d \n&quot; , new_socket , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));

			//send new connection greeting message
			if( send(new_socket, message, strlen(message), 0) != strlen(message) )
			{
				perror(&quot;send&quot;);
			}

			puts(&quot;Welcome message sent successfully&quot;);

			//add new socket to array of sockets
			for (i = 0; i &lt; max_clients; i++)
			{
				s = client_socket[i];
				if (s == 0)
				{
					client_socket[i] = new_socket;
					printf(&quot;Adding to list of sockets as %d\n&quot; , i);
					i = max_clients;
				}
			}
		}

		//else its some IO operation on some other socket :)
		for (i = 0; i &lt; max_clients; i++)
		{
			s = client_socket[i];

			if (FD_ISSET( s , &amp;readfds))
			{
				//Check if it was for closing , and also read the incoming message
				if ((valread = read( s , buffer, 1024)) == 0)
				{
					//Somebody disconnected , get his details and print
					getpeername(s , (struct sockaddr*)&amp;address , (socklen_t*)&amp;addrlen);
					printf(&quot;Host disconnected , ip %s , port %d \n&quot; , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));

					//Close the socket and mark as 0 in list for reuse
					close( s );
					client_socket[i] = 0;
				}

				//Echo back the message that came in
				else
				{
					//set the terminating NULL byte on the end of the data read
					buffer[valread] = '&#92;&#48;';
					send( s , buffer , strlen(buffer) , 0 );
				}
			}
		}
	}

	return 0;
}
</pre>
<p>Compile and run the above program. Then connect to it using telnet from 3 different terminals.</p>
<pre class="brush: bash; title: Code; notranslate">
$ telnet localhost 8888
</pre>
<p>Now whatever you type and send to server will be send back as it is, or echoed. </p>
<p>The server terminal would show details of connections like this :</p>
<pre class="brush: bash; title: Code; notranslate">
Waiting for connections...
New connection , socket fd is 4 , ip is : 127.0.0.1 , port : 57831
Welcome message sent successfully
Adding to list of sockets as 0
New connection , socket fd is 5 , ip is : 127.0.0.1 , port : 57832
Welcome message sent successfully
Adding to list of sockets as 1
New connection , socket fd is 6 , ip is : 127.0.0.1 , port : 57833
Welcome message sent successfully
Adding to list of sockets as 2
New connection , socket fd is 7 , ip is : 127.0.0.1 , port : 57834
Welcome message sent successfully
</pre>
<p>The client terminal can be like this </p>
<pre class="brush: bash; title: Code; notranslate">

$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
ECHO Daemon v1.0
ccc
ccc
ddd
ddd
fff
fff
</pre>
<p>There are other functions that can perform tasks similar to select. pselect , poll , ppoll</p>
<p><strong>References</strong></p>
<p>1. <a target="_blank" href="http://pubs.opengroup.org/onlinepubs/7908799/xsh/select.html" >http://pubs.opengroup.org/onlinepubs/7908799/xsh/select.html</a></p>
<p>2. <a target="_blank" href="http://linux.die.net/man/2/select" >http://linux.die.net/man/2/select</a></p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1297&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/handle-multiple-socket-connections-with-fd_set-and-select-on-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Beginners guide to socket programming in C on Linux</title>
		<link>http://www.binarytides.com/blog/beginners-guide-to-socket-programming-in-c-on-linux/</link>
		<comments>http://www.binarytides.com/blog/beginners-guide-to-socket-programming-in-c-on-linux/#comments</comments>
		<pubDate>Sat, 24 Dec 2011 07:59:48 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1271</guid>
		<description><![CDATA[What is this about This is a quick guide/tutorial to learning socket programming in C language on a Linux system. &#8220;Linux&#8221; because the code snippets shown over here will work only on a Linux system and not on Windows. The windows api to socket programming is called winsock and we shall go through it in another tutorial. Sockets are the fundamental &#8220;things&#8221; behind any kind of network communications done by your computer. For example when [...]]]></description>
			<content:encoded><![CDATA[<h3>What is this about</h3>
<p>This is a quick guide/tutorial to learning socket programming in C language on a Linux system. &#8220;Linux&#8221; because the code snippets shown over here will work only on a Linux system and not on Windows. The windows api to socket programming is called winsock and we shall go through it in another tutorial.</p>
<p>Sockets are the fundamental &#8220;things&#8221; behind any kind of network communications done by your computer. For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype. Any network communication goes through a socket.</p>
<h3>Before you begin</h3>
<p>This tutorial assumes that you have basic knowledge of C and pointers. You will need to have gcc compiler installed on your Linux system. An IDE along with gcc would be great. I would recommend geany as you can quickly edit and run single file programs in it without much configurations. On ubuntu you can do a sudo apt-get install geany on the terminal.</p>
<p>All along the tutorial there are code snippets to demonstrate some concepts. You can run those code snippets in geany rightaway and test the results to better understand the concepts.</p>
<h3>Creating a socket</h3>
<p>This first thing to do is create a socket. The <code>socket()</code> function does this.<br />
Here is a code sample :</p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt;
#include&lt;sys/socket.h&gt; 

int main(int argc , char *argv[])
{
	int socket_desc;
	socket_desc = socket(AF_INET , SOCK_STREAM , 0);

	if (socket_desc == -1)
	{
		printf(&quot;Could not create socket&quot;);
	}

	return 0;
}
</pre>
<p>Function <code>socket()</code> creates a socket and returns a socket descriptor which can be used in other network commands. The above code will create a socket of :</p>
<p>Address Family : AF_INET (this is IP version 4)<br />
Type : SOCK_STREAM (this means connection oriented TCP protocol)<br />
Protocol : 0 [ or IPPROTO_IP This is IP protocol]</p>
<p>Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server using this socket. We can connect to www.google.com</p>
<p><strong>Note</strong></p>
<p>Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.</p>
<h3>Connect to a Server</h3>
<p>We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to.</p>
<p>To connect to a remote server we need to do a couple of things. First is create a sockaddr_in structure with proper values filled in. Lets create one for ourselves :</p>
<pre class="brush: cpp; title: Code; notranslate">
struct sockaddr_in server;
</pre>
<p>Have a look at the structure</p>
<pre class="brush: cpp; title: Code; notranslate">
// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

struct in_addr {
    unsigned long s_addr;          // load with inet_pton()
};

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};
</pre>
<p>The sockaddr_in has a member called sin_addr of type in_addr which has a s_addr which is nothing but a long. It contains the IP address in long format.</p>
<p>Function <code>inet_addr</code> is a very handy function to convert an IP address to a long format. This is how you do it :</p>
<pre class="brush: cpp; title: Code; notranslate">
server.sin_addr.s_addr = inet_addr(&quot;74.125.235.20&quot;);
</pre>
<p>So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample. A little later on we shall see how to find out the ip address of a given domain name.</p>
<p>The last thing needed is the <code>connect</code> function. It needs a socket and a sockaddr structure to connect to. Here is a code sample.</p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt;
#include&lt;sys/socket.h&gt;
#include&lt;arpa/inet.h&gt;	//inet_addr

int main(int argc , char *argv[])
{
	int socket_desc;
	struct sockaddr_in server;

	//Create socket
	socket_desc = socket(AF_INET , SOCK_STREAM , 0);
	if (socket_desc == -1)
	{
		printf(&quot;Could not create socket&quot;);
	}

	server.sin_addr.s_addr = inet_addr(&quot;74.125.235.20&quot;);
	server.sin_family = AF_INET;
	server.sin_port = htons( 80 );

	//Connect to remote server
	if (connect(socket_desc , (struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;connect error&quot;);
		return 1;
	}

	puts(&quot;Connected&quot;);
	return 0;
}
</pre>
<p>It cannot be any simpler. It creates a socket and then connects. If you run the program it should show Connected.<br />
Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection.</p>
<p>OK , so we are now connected. Lets do the next thing , sending some data to the remote server.</p>
<p><strong>Quick Note</strong></p>
<p>The concept of &#8220;connections&#8221; apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable &#8220;stream&#8221; of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by other data.</p>
<p>Other sockets like UDP , ICMP , ARP dont have a concept of &#8220;connection&#8221;. These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.</p>
<h3>Sending Data</h3>
<p>Function <code>send</code> will simply send data. It needs the socket descriptor , the data to send and its size.<br />
Here is a very simple example of sending some data to google.com ip :</p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt;
#include&lt;string.h&gt;	//strlen
#include&lt;sys/socket.h&gt;
#include&lt;arpa/inet.h&gt;	//inet_addr

int main(int argc , char *argv[])
{
	int socket_desc;
	struct sockaddr_in server;
	char *message;

	//Create socket
	socket_desc = socket(AF_INET , SOCK_STREAM , 0);
	if (socket_desc == -1)
	{
		printf(&quot;Could not create socket&quot;);
	}

	server.sin_addr.s_addr = inet_addr(&quot;74.125.235.20&quot;);
	server.sin_family = AF_INET;
	server.sin_port = htons( 80 );

	//Connect to remote server
	if (connect(socket_desc , (struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;connect error&quot;);
		return 1;
	}

	puts(&quot;Connected\n&quot;);

	//Send some data
	message = &quot;GET / HTTP/1.1\r\n\r\n&quot;;
	if( send(socket_desc , message , strlen(message) , 0) &lt; 0)
	{
		puts(&quot;Send failed&quot;);
		return 1;
	}
	puts(&quot;Data Send\n&quot;);

	return 0;
}
</pre>
<p>In the above example , we first connect to an ip address and then send the string message &#8220;GET / HTTP/1.1\r\n\r\n&#8221; to it.<br />
The message is actually a http command to fetch the mainpage of a website.</p>
<p>Now that we have send some data , its time to receive a reply from the server. So lets do it.</p>
<p><strong>Note</strong></p>
<p>When sending data to a socket you are basically writing data to that socket. This is similar to writing data to a file. Hence you can also use the <code>write</code> function to send data to a socket. Later in this tutorial we shall use write function to send data.</p>
<h3>Receiving Data</h3>
<p>Function <code>recv</code> is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.</p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt;
#include&lt;string.h&gt;	//strlen
#include&lt;sys/socket.h&gt;
#include&lt;arpa/inet.h&gt;	//inet_addr

int main(int argc , char *argv[])
{
	int socket_desc;
	struct sockaddr_in server;
	char *message , server_reply[2000];

	//Create socket
	socket_desc = socket(AF_INET , SOCK_STREAM , 0);
	if (socket_desc == -1)
	{
		printf(&quot;Could not create socket&quot;);
	}

	server.sin_addr.s_addr = inet_addr(&quot;74.125.235.20&quot;);
	server.sin_family = AF_INET;
	server.sin_port = htons( 80 );

	//Connect to remote server
	if (connect(socket_desc , (struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;connect error&quot;);
		return 1;
	}

	puts(&quot;Connected\n&quot;);

	//Send some data
	message = &quot;GET / HTTP/1.1\r\n\r\n&quot;;
	if( send(socket_desc , message , strlen(message) , 0) &lt; 0)
	{
		puts(&quot;Send failed&quot;);
		return 1;
	}
	puts(&quot;Data Send\n&quot;);

	//Receive a reply from the server
	if( recv(socket_desc, server_reply , 2000 , 0) &lt; 0)
	{
		puts(&quot;recv failed&quot;);
	}
	puts(&quot;Reply received\n&quot;);
	puts(server_reply);

	return 0;
}
</pre>
<p>Here is the output of the above code :</p>
<pre class="brush: bash; title: Code; notranslate">
Connected

Data Send

Reply received

HTTP/1.1 302 Found
Location: http://www.google.co.in/
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=0edd21a16f0db219:FF=0:TM=1324644706:LM=1324644706:S=z6hDC9cZfGEowv_o; expires=Sun, 22-Dec-2013 12:51:46 GMT; path=/; domain=.google.com
Date: Fri, 23 Dec 2011 12:51:46 GMT
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

&lt;HTML&gt;&lt;HEAD&gt;&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html;charset=utf-8&quot;&gt;
&lt;TITLE&gt;302 Moved&lt;/TITLE&gt;&lt;/HEAD&gt;&lt;BODY&gt;
&lt;H1&gt;302 Moved&lt;/H1&gt;
The document has moved
&lt;A HREF=&quot;http://www.google.co.in/&quot;&gt;here&lt;/A&gt;.
&lt;/BODY&gt;&lt;/HTML&gt;
</pre>
<p>We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com replied with the content of the page we requested. Quite simple!</p>
<p><strong>Note</strong></p>
<p>When receiving data on a socket , we are basically reading the data on the socket. This is similar to reading data from a file. So we can also use the <code>read</code> function to read data on a socket. For example :</p>
<pre class="brush: cpp; title: Code; notranslate">
read(socket_desc, server_reply , 2000);
</pre>
<p>Now that we have received our reply, its time to close the socket.</p>
<h3>Close socket</h3>
<p>Function <code>close</code> is used to close the socket. Need to include the unistd.h header file for this.</p>
<pre class="brush: cpp; title: Code; notranslate">
close(socket_desc);
</pre>
<p>Thats it.</p>
<h3>Lets Revise</h3>
<p>So in the above example we learned how to :<br />
1. Create a socket<br />
2. Connect to remote server<br />
3. Send some data<br />
4. Receive a reply</p>
<p>Its useful to know that your web browser also does the same thing when you open www.google.com<br />
This kind of socket activity represents a <strong>CLIENT</Strong>. A client is a system that connects to a remote system to fetch or retrieve data.</p>
<p>The other kind of socket activity is called a <strong>SERVER</strong>. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.</p>
<p>Now its time to do some server tasks using sockets. But before we move ahead there are a few side topics that should be covered just incase you need them.</p>
<h3>Get IP address of a hostname/domain</h3>
<p>When connecting to a remote host , it is necessary to have its IP address. Function <code>gethostbyname</code> is used for this purpose. It takes the domain name as the parameter and returns a structure of type hostent. This structure has the ip information. It is present in <code>netdb.h</code>. Lets have a look at this structure </p>
<pre class="brush: cpp; title: Code; notranslate">
/* Description of data base entry for a single host.  */
struct hostent
{
  char *h_name;			/* Official name of host.  */
  char **h_aliases;		/* Alias list.  */
  int h_addrtype;		/* Host address type.  */
  int h_length;			/* Length of address.  */
  char **h_addr_list;		/* List of addresses from name server.  */
};
</pre>
<p>The <code>h_addr_list</code> has the IP addresses. So now lets have some code to use them.</p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt; //printf
#include&lt;string.h&gt; //strcpy
#include&lt;sys/socket.h&gt;
#include&lt;netdb.h&gt;	//hostent
#include&lt;arpa/inet.h&gt;

int main(int argc , char *argv[])
{
	char *hostname = &quot;www.google.com&quot;;
	char ip[100];
	struct hostent *he;
	struct in_addr **addr_list;
	int i;

	if ( (he = gethostbyname( hostname ) ) == NULL)
	{
		//gethostbyname failed
		herror(&quot;gethostbyname&quot;);
		return 1;
	}

	//Cast the h_addr_list to in_addr , since h_addr_list also has the ip address in long format only
	addr_list = (struct in_addr **) he-&gt;h_addr_list;

	for(i = 0; addr_list[i] != NULL; i++)
	{
		//Return the first one;
		strcpy(ip , inet_ntoa(*addr_list[i]) );
	}

	printf(&quot;%s resolved to : %s&quot; , hostname , ip);
	return 0;
}
</pre>
<p>Output of the code would look like :</p>
<pre class="brush: bash; title: Code; notranslate">
www.google.com resolved to : 74.125.235.20
</pre>
<p>So the above code can be used to find the ip address of any domain name. Then the ip address can be used to make a connection using a socket.</p>
<p>Function <code>inet_ntoa</code> will convert an IP address in long format to dotted format. This is just the opposite of <code>inet_addr</code>.</p>
<p>So far we have see some important structures that are used. Lets revise them :</p>
<p>1. <code>sockaddr_in</code> &#8211; Connection information. Used by connect , send , recv etc.<br />
2. <code>in_addr</code> &#8211; Ip address in long format<br />
3. <code>sockaddr</code><br />
4. <code>hostent</code> &#8211; The ip addresses of a hostname. Used by gethostbyname</p>
<h3>Server Concepts</h3>
<p>OK now onto server things. Servers basically do the following :</p>
<p>1. Open a socket<br />
2. Bind to a address(and port).<br />
3. Listen for incoming connections.<br />
4. Accept connections<br />
5. Read/Send</p>
<p>We have already learnt how to open a socket. So the next thing would be to bind it.</p>
<h3>Bind a socket</h3>
<p>Function <code>bind</code> can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.</p>
<p>Lets see a code example :</p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt;
#include&lt;sys/socket.h&gt;
#include&lt;arpa/inet.h&gt;	//inet_addr

int main(int argc , char *argv[])
{
	int socket_desc;
	struct sockaddr_in server;

	//Create socket
	socket_desc = socket(AF_INET , SOCK_STREAM , 0);
	if (socket_desc == -1)
	{
		printf(&quot;Could not create socket&quot;);
	}

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons( 8888 );

	//Bind
	if( bind(socket_desc,(struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;bind failed&quot;);
	}
	puts(&quot;bind done&quot;);

	return 0;
}
</pre>
<p>Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application. </p>
<p>This makes it obvious that you cannot have 2 sockets bound to the same port.</p>
<h3>Listen for connections</h3>
<p>After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function <code>listen</code> is used to put the socket in listening mode. Just add the following line after bind.</p>
<pre class="brush: cpp; title: Code; notranslate">
//Listen
listen(socket_desc , 3);
</pre>
<p>Thats all. Now comes the main part of accepting new connections.</p>
<h3>Accept connection</h3>
<p>Function <code>accept</code> is used for this. Here is the code</p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt;
#include&lt;sys/socket.h&gt;
#include&lt;arpa/inet.h&gt;	//inet_addr

int main(int argc , char *argv[])
{
	int socket_desc , new_socket , c;
	struct sockaddr_in server , client;

	//Create socket
	socket_desc = socket(AF_INET , SOCK_STREAM , 0);
	if (socket_desc == -1)
	{
		printf(&quot;Could not create socket&quot;);
	}

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons( 8888 );

	//Bind
	if( bind(socket_desc,(struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;bind failed&quot;);
	}
	puts(&quot;bind done&quot;);

	//Listen
	listen(socket_desc , 3);

	//Accept and incoming connection
	puts(&quot;Waiting for incoming connections...&quot;);
	c = sizeof(struct sockaddr_in);
	new_socket = accept(socket_desc, (struct sockaddr *)&amp;client, (socklen_t*)&amp;c);
	if (new_socket&lt;0)
	{
		perror(&quot;accept failed&quot;);
	}

	puts(&quot;Connection accepted&quot;);

	return 0;
}
</pre>
<p><strong>Output</strong></p>
<p>Run the program. It should show</p>
<pre class="brush: bash; title: Code; notranslate">
bind done
Waiting for incoming connections...
</pre>
<p>So now this program is waiting for incoming connections on port 8888. Dont close this program , keep it running.<br />
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type </p>
<pre class="brush: bash; title: Code; notranslate">
$ telnet localhost 8888
</pre>
<p>On the terminal you shall get</p>
<pre class="brush: bash; title: Code; notranslate">
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
</pre>
<p>And the server output will show</p>
<pre class="brush: bash; title: Code; notranslate">
bind done
Waiting for incoming connections...
Connection accepted
</pre>
<p>So we can see that the client connected to the server. Try the above process till you get it perfect.</p>
<p><strong>Note</strong></p>
<p>You can get the ip address of client and the port of connection by using the sockaddr_in structure passed to accept function. It is very simple :</p>
<pre class="brush: cpp; title: Code; notranslate">
char *client_ip = inet_ntoa(client.sin_addr);
int client_port = ntohs(client.sin_port);
</pre>
<p>We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client. </p>
<p>We can simply use the <code>write</code> function to write something to the socket of the incoming connection and the client should see it. Here is an example :</p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt;
#include&lt;string.h&gt;	//strlen
#include&lt;sys/socket.h&gt;
#include&lt;arpa/inet.h&gt;	//inet_addr
#include&lt;unistd.h&gt;	//write

int main(int argc , char *argv[])
{
	int socket_desc , new_socket , c;
	struct sockaddr_in server , client;
	char *message;

	//Create socket
	socket_desc = socket(AF_INET , SOCK_STREAM , 0);
	if (socket_desc == -1)
	{
		printf(&quot;Could not create socket&quot;);
	}

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons( 8888 );

	//Bind
	if( bind(socket_desc,(struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;bind failed&quot;);
		return 1;
	}
	puts(&quot;bind done&quot;);

	//Listen
	listen(socket_desc , 3);

	//Accept and incoming connection
	puts(&quot;Waiting for incoming connections...&quot;);
	c = sizeof(struct sockaddr_in);
	new_socket = accept(socket_desc, (struct sockaddr *)&amp;client, (socklen_t*)&amp;c);
	if (new_socket&lt;0)
	{
		perror(&quot;accept failed&quot;);
		return 1;
	}

	puts(&quot;Connection accepted&quot;);

	//Reply to the client
	message = &quot;Hello Client , I have received your connection. But I have to go now, bye\n&quot;;
	write(new_socket , message , strlen(message));

	return 0;
}
</pre>
<p>Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :</p>
<pre class="brush: bash; title: Code; notranslate">
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello Client , I have received your connection. But I have to go now, bye
Connection closed by foreign host.
</pre>
<p>So the client(telnet) received a reply from server.</p>
<p>We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections. </p>
<p>It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the <code>accept</code> in a loop so that it can receive incoming connections all the time.</p>
<h3>Live Server</h3>
<p>So a live server will be alive for all time. Lets code this up :</p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt;
#include&lt;string.h&gt;	//strlen
#include&lt;sys/socket.h&gt;
#include&lt;arpa/inet.h&gt;	//inet_addr
#include&lt;unistd.h&gt;	//write

int main(int argc , char *argv[])
{
	int socket_desc , new_socket , c;
	struct sockaddr_in server , client;
	char *message;

	//Create socket
	socket_desc = socket(AF_INET , SOCK_STREAM , 0);
	if (socket_desc == -1)
	{
		printf(&quot;Could not create socket&quot;);
	}

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons( 8888 );

	//Bind
	if( bind(socket_desc,(struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;bind failed&quot;);
		return 1;
	}
	puts(&quot;bind done&quot;);

	//Listen
	listen(socket_desc , 3);

	//Accept and incoming connection
	puts(&quot;Waiting for incoming connections...&quot;);
	c = sizeof(struct sockaddr_in);
	while( (new_socket = accept(socket_desc, (struct sockaddr *)&amp;client, (socklen_t*)&amp;c)) )
	{
		puts(&quot;Connection accepted&quot;);

		//Reply to the client
		message = &quot;Hello Client , I have received your connection. But I have to go now, bye\n&quot;;
		write(new_socket , message , strlen(message));
	}

	if (new_socket&lt;0)
	{
		perror(&quot;accept failed&quot;);
		return 1;
	}

	return 0;
}
</pre>
<p>We havent done a lot there. Just the accept was put in a loop.</p>
<p>Now run the program in 1 terminal , and open 3 other terminals. From each of the 3 terminal do a telnet to the server port.</p>
<p>Each of the telnet terminal would show :</p>
<pre class="brush: bash; title: Code; notranslate">
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello Client , I have received your connection. But I have to go now, bye
</pre>
<p>And the server terminal would show</p>
<pre class="brush: bash; title: Code; notranslate">
bind done
Waiting for incoming connections...
Connection accepted
Connection accepted
Connection accepted
</pre>
<p>So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program.<br />
All telnet terminals would show &#8220;Connection closed by foreign host.&#8221;<br />
Good so far. But still there is not effective communication between the server and the client.</p>
<p>The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections , and handle multiple connections together.</p>
<h3>Handling Connections</h3>
<p>To handle every connection we need a separate handling code to run along with the main server accepting connections.<br />
One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.</p>
<p>On Linux threading can be done with the pthread (posix threads) library. It would be good to read some small tutorial about it if you dont know anything about it. However the usage is not very complicated.</p>
<p>We shall now use threads to create handlers for each connection the server accepts. Lets do it pal.</p>
<pre class="brush: cpp; title: Code; notranslate">

#include&lt;stdio.h&gt;
#include&lt;string.h&gt;	//strlen
#include&lt;stdlib.h&gt;	//strlen
#include&lt;sys/socket.h&gt;
#include&lt;arpa/inet.h&gt;	//inet_addr
#include&lt;unistd.h&gt;	//write

#include&lt;pthread.h&gt; //for threading , link with lpthread

void *connection_handler(void *);

int main(int argc , char *argv[])
{
	int socket_desc , new_socket , c , *new_sock;
	struct sockaddr_in server , client;
	char *message;

	//Create socket
	socket_desc = socket(AF_INET , SOCK_STREAM , 0);
	if (socket_desc == -1)
	{
		printf(&quot;Could not create socket&quot;);
	}

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons( 8888 );

	//Bind
	if( bind(socket_desc,(struct sockaddr *)&amp;server , sizeof(server)) &lt; 0)
	{
		puts(&quot;bind failed&quot;);
		return 1;
	}
	puts(&quot;bind done&quot;);

	//Listen
	listen(socket_desc , 3);

	//Accept and incoming connection
	puts(&quot;Waiting for incoming connections...&quot;);
	c = sizeof(struct sockaddr_in);
	while( (new_socket = accept(socket_desc, (struct sockaddr *)&amp;client, (socklen_t*)&amp;c)) )
	{
		puts(&quot;Connection accepted&quot;);

		//Reply to the client
		message = &quot;Hello Client , I have received your connection. And now I will assign a handler for you\n&quot;;
		write(new_socket , message , strlen(message));

		pthread_t sniffer_thread;
		new_sock = malloc(1);
		*new_sock = new_socket;

		if( pthread_create( &amp;sniffer_thread , NULL ,  connection_handler , (void*) new_sock) &lt; 0)
		{
			perror(&quot;could not create thread&quot;);
			return 1;
		}

		//Now join the thread , so that we dont terminate before the thread
		//pthread_join( sniffer_thread , NULL);
		puts(&quot;Handler assigned&quot;);
	}

	if (new_socket&lt;0)
	{
		perror(&quot;accept failed&quot;);
		return 1;
	}

	return 0;
}

/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
	//Get the socket descriptor
	int sock = *(int*)socket_desc;

	char *message;

	//Send some messages to the client
	message = &quot;Greetings! I am your connection handler\n&quot;;
	write(sock , message , strlen(message));

	message = &quot;Its my duty to communicate with you&quot;;
	write(sock , message , strlen(message));

	//Free the socket pointer
	free(socket_desc);

	return 0;
}
</pre>
<p>Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.</p>
<p>The telnet terminals would show :</p>
<pre class="brush: bash; title: Code; notranslate">
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello Client , I have received your connection. And now I will assign a handler for you
Hello I am your connection handler
Its my duty to communicate with you
</pre>
<p>This one looks good , but the communication handler is also quite dumb. After the greeting it terminates. It should stay alive and keep communicating with the client.</p>
<p>One way to do this is by making the connection handler wait for some message from a client as long as the client is connected. If the client disconnects , the connection handler ends.</p>
<p>So the connection handler can be rewritten like this :</p>
<pre class="brush: cpp; title: Code; notranslate">

/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
	//Get the socket descriptor
	int sock = *(int*)socket_desc;
	int read_size;
	char *message , client_message[2000];

	//Send some messages to the client
	message = &quot;Greetings! I am your connection handler\n&quot;;
	write(sock , message , strlen(message));

	message = &quot;Now type something and i shall repeat what you type \n&quot;;
	write(sock , message , strlen(message));

	//Receive a message from client
	while( (read_size = recv(sock , client_message , 2000 , 0)) &gt; 0 )
	{
		//Send the message back to client
		write(sock , client_message , strlen(client_message));
	}

	if(read_size == 0)
	{
		puts(&quot;Client disconnected&quot;);
		fflush(stdout);
	}
	else if(read_size == -1)
	{
		perror(&quot;recv failed&quot;);
	}

	//Free the socket pointer
	free(socket_desc);

	return 0;
}
</pre>
<p>The above connection handler takes some input from the client and replies back with the same. Simple! Here is how the telnet output might look</p>
<pre class="brush: bash; title: Code; notranslate">
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello Client , I have received your connection. And now I will assign a handler for you
Greetings! I am your connection handler
Now type something and i shall repeat what you type
Hello
Hello
How are you
How are you
I am fine
I am fine
</pre>
<p>So now we have a server thats communicative. Thats useful now.</p>
<p><strong>Note</strong></p>
<p>When compiling programs that use the pthread library you need to link the library. This is done like this :</p>
<p><code>gcc program.c -lpthread</code></p>
<h3>Conclusion</h3>
<p>By now you must have learned the basics of socket programming in C. You can try out some experiments like writing a chat client or something similar.</p>
<p>If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1271&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/beginners-guide-to-socket-programming-in-c-on-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Gui whois client in python with wxpython</title>
		<link>http://www.binarytides.com/blog/gui-whois-client-in-python-with-wxpython/</link>
		<comments>http://www.binarytides.com/blog/gui-whois-client-in-python-with-wxpython/#comments</comments>
		<pubDate>Fri, 23 Dec 2011 07:09:11 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Sockets]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1268</guid>
		<description><![CDATA[Wxpython is the python port of wxwidgets gui library. On ubuntu wxpython can be installed from synaptic. On windows it can be downloaded from the website wxpython.org And here is a small program that pops up a simple window , to take a domain name and perform a whois for that domain.]]></description>
			<content:encoded><![CDATA[<p>Wxpython is the python port of wxwidgets gui library. On ubuntu wxpython can be installed from synaptic. On windows it can be downloaded from the website <a target="_blank" href="http://www.wxpython.org/" >wxpython.org</a></p>
<p>And here is a small program that pops up a simple window , to take a domain name and perform a whois for that domain.</p>
<pre class="brush: python; title: Code; notranslate">
#!/usr/bin/python

#@author Silver Moon
#@email m00n.silv3r@gmail.com

import wx
import socket
import thread

#A class which will open a window , it is a wx.Frame type of window
class WhoisForm(wx.Frame):
    def __init__(self, parent):

        #Call the parent constructor
        wx.Frame.__init__(self, parent, -1 , size=(500,350), title=&quot;Whois Utility&quot;)

        #Create some components like the GUI
        self.InitComponents()
    #End

    def InitComponents(self):
        #Now onto other GUI creation
        panel = wx.Panel(self, -1)

        #This sizer shall contain the individual controls
        fgs = wx.FlexGridSizer(3, 2, 9, 25)     

        #Create some static text controls
        server = wx.StaticText(panel, -1, 'Enter Hostname')
        result = wx.StaticText(panel, -1, 'Whois Result')

        #Create some text boxes and buttons , remember they all belong to the panel
        self.txtServer = wx.TextCtrl(panel, -1)

        btnWhois = wx.Button(panel ,  20 , &quot;Whois&quot;)
        self.Bind(wx.EVT_BUTTON, self.OnButtonWhois, btnWhois)
        btnWhois.SetToolTipString(&quot;Click to get whois information for the domain name.&quot;)
        self.button_whois = btnWhois

        self.txtResult = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)

        #Add the input field and submit button to a Box Sizer since the must stay together
        space = wx.BoxSizer()
        #Text field should be expandable
        space.Add(self.txtServer , 1 , wx.RIGHT , 10)
        #Button should not expand and stay to right
        space.Add(btnWhois , 0 , wx.ALIGN_RIGHT)

        #Create a list to add these controls to the sizer :)
        mybag = [
                    (server) , (space ,1 , wx.EXPAND) , \
                    (result) , (self.txtResult , 1 , wx.EXPAND), \
                ]

        fgs.AddMany(mybag)

        #Define the parts that grow and shrink on resizing
        fgs.AddGrowableRow(1, 1)
        fgs.AddGrowableCol(1, 1)
        box = wx.BoxSizer()
        box.Add(fgs, 1 , wx.EXPAND | wx.ALL , 20)
        panel.SetSizer(box)

        sizer = wx.BoxSizer()
        sizer.Add(panel, 1, wx.EXPAND)
        self.SetSizer(sizer)

        wx.CallAfter(self.Layout)
    #End

    def get_focus(self) :
		self.button_whois.SetFocus()

    #Event handler for the button
    def OnButtonWhois(self , evt):
        #Start a worker thread so that GUI is not kept busy , like the button being pressed
        thread.start_new_thread(self.worker_thread , ())
    #End

    def worker_thread(self) :
		#Get the domain name from the input control
        domain = self.txtServer.GetValue()
        if domain == '':
            wx.MessageBox('Please Enter the domain name','Error')
            return

        #Get the whois data
        whois_data = self.perform_whois(domain)

        #Fill the result box
        r = self.txtResult
        r.SetValue('')
        r.AppendText(whois_data)

    #Function to perform the whois on a domain name
    def perform_whois(self , domain):

        #remove http and www
        domain = domain.replace('http://','')
        domain = domain.replace('www.','')

        #get the extension , .com , .org , .edu
        ext = domain[-3:]

        #If top level domain .com .org .net
        if(ext == 'com' or ext == 'org' or ext == 'net'):
            whois = 'whois.internic.net'
            s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
            s.connect((whois , 43))
            s.send(domain + '\r\n')
            msg = ''
            while len(msg) &lt; 10000:
                chunk = s.recv(100)
                if(chunk == ''):
                    break
                msg = msg + chunk

            #Now scan the reply for the whois server
            lines = msg.splitlines()
            for line in lines:
                if ':' in line:
                    words = line.split(':')
                    if 'whois.' in words[1] and 'Whois' in words[0]:
                        whois = words[1].strip()
                        break;

        #Or Country level - contact whois.iana.org to find the whois server of a particular TLD
        else:
			#Break again like , co.uk to uk
            ext = domain.split('.')[-1]

            #This will tell the whois server for the particular country
            whois = 'whois.iana.org'
            s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
            s.connect((whois , 43))
            s.send(ext + '\r\n')

            #Receive some reply
            msg = ''
            while len(msg) &lt; 10000:
                chunk = s.recv(100)
                if(chunk == ''):
                    break
                msg = msg + chunk

            #Now search the reply for a whois server
            lines = msg.splitlines()
            for line in lines:
                if ':' in line:
                    words = line.split(':')
                    if 'whois.' in words[1] and 'Whois Server (port 43)' in words[0]:
                        whois = words[1].strip()
                        break;

        #Now contact the final whois server
        s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
        s.connect((whois , 43))
        s.send(domain + '\r\n\r\n')
        msg = ''

        #Receive the reply
        while len(msg) &lt; 10000:
            chunk = s.recv(100)
            if(chunk == ''):
                break
            msg = msg + chunk

        #Return the reply
        return msg

    #End
#End

#Create an application
app = wx.App()

#Create the windows :)
window = WhoisForm(None)
window.Show()
window.get_focus()

#Start application event loop
app.MainLoop()
</pre>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1268&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/gui-whois-client-in-python-with-wxpython/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Whois client code in C with Linux sockets</title>
		<link>http://www.binarytides.com/blog/whois-client-code-in-c-with-linux-sockets/</link>
		<comments>http://www.binarytides.com/blog/whois-client-code-in-c-with-linux-sockets/#comments</comments>
		<pubDate>Fri, 23 Dec 2011 06:47:17 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1266</guid>
		<description><![CDATA[A whois client is a program that will simply fetch the whois information for a domain/ip address from the whois servers. The code over here works according to the algorithm discussed here. Code hostname_to_ip &#8211; This is a simple function to get an IP of a domain. str_replace &#8211; This is a generic string processing function that is used to search for a string in another big string and replace it with another string. Output]]></description>
			<content:encoded><![CDATA[<p>A whois client is a program that will simply fetch the whois information for a domain/ip address from the whois servers. The code over here works according to the algorithm discussed here.</p>
<p><strong>Code</strong></p>
<pre class="brush: cpp; title: Code; notranslate">
/*
 * @brief
 * Whois client program
 *
 * @details
 * This program shall perform whois for a domain and get you the whois data of that domain
 *
 * @author Silver Moon ( m00n.silv3r@gmail.com )
 * */

#include&lt;stdio.h&gt;	//scanf , printf
#include&lt;string.h&gt;	//strtok
#include&lt;stdlib.h&gt;	//realloc
#include&lt;sys/socket.h&gt;	//socket
#include&lt;netinet/in.h&gt; //sockaddr_in
#include&lt;arpa/inet.h&gt;	//getsockname
#include&lt;netdb.h&gt;	//hostent
#include&lt;unistd.h&gt;	//close

int get_whois_data(char * , char **);
int hostname_to_ip(char * , char *);
int whois_query(char * , char * , char **);
char *str_replace(char *search , char *replace , char *subject );

int main(int argc , char *argv[])
{
	char domain[100] , *data = NULL;

	printf(&quot;Enter domain name to whois : &quot;);
	scanf(&quot;%s&quot; , domain);

	get_whois_data(domain , &amp;data);

	//puts(data);
	return 0;
}

/*
 * Get the whois data of a domain
 * */
int get_whois_data(char *domain , char **data)
{
	char ext[1024] , *pch , *response = NULL , *response_2 = NULL , *wch , *dt;

	//remove &quot;http://&quot; and &quot;www.&quot;
	domain = str_replace(&quot;http://&quot; , &quot;&quot; , domain);
	domain = str_replace(&quot;www.&quot; , &quot;&quot; , domain);

	//get the extension , com , org , edu
	dt = strdup(domain);
	if(dt == NULL)
	{
		printf(&quot;strdup failed&quot;);
	}
	pch = (char*)strtok(dt , &quot;.&quot;);
	while(pch != NULL)
	{
		strcpy(ext , pch);
		pch = strtok(NULL , &quot;.&quot;);
	}

	//This will tell the whois server for the particular TLD like com , org
	if(whois_query(&quot;whois.iana.org&quot; , ext , &amp;response))
	{
		printf(&quot;Whois query failed&quot;);
	}

	//Now analysze the response :)
	pch = strtok(response , &quot;\n&quot;);
	while(pch != NULL)
	{
		//Check if whois line
		wch = strstr(pch , &quot;whois.&quot;);
		if(wch != NULL)
		{
			break;
		}

		//Next line please
		pch = strtok(NULL , &quot;\n&quot;);
	}

	//Now we have the TLD whois server in wch , query again
	//This will provide minimal whois information along with the parent whois server of the specific domain :)
	free(response);
	//This should not be necessary , but segmentation fault without this , why ?
	response = NULL;
	if(wch != NULL)
	{
		printf(&quot;\nTLD Whois server is : %s&quot; , wch);
		if(whois_query(wch , domain , &amp;response))
		{
			printf(&quot;Whois query failed&quot;);
		}
	}
	else
	{
		printf(&quot;\nTLD whois server for %s not found&quot; , ext);
		return 1;
	}

	response_2 = strdup(response);

	//Again search for a whois server in this response. :)
	pch = strtok(response , &quot;\n&quot;);
	while(pch != NULL)
	{
		//Check if whois line
		wch = strstr(pch , &quot;whois.&quot;);
		if(wch != NULL)
		{
			break;
		}

		//Next line please
		pch = strtok(NULL , &quot;\n&quot;);
	}

	/*
	 * If a registrar whois server is found then query it
	 * */
	if(wch)
	{
		//Now we have the registrar whois server , this has the direct full information of the particular domain
		//so lets query again

		printf(&quot;\nRegistrar Whois server is : %s&quot; , wch);

		if(whois_query(wch , domain , &amp;response))
		{
			printf(&quot;Whois query failed&quot;);
		}

		printf(&quot;\n%s&quot; , response);
	}

	/*
	 * otherwise echo the output from the previous whois result
	 * */
	else
	{
		printf(&quot;%s&quot; , response_2);
	}
	return 0;
}

/*
 * Perform a whois query to a server and record the response
 * */
int whois_query(char *server , char *query , char **response)
{
	char ip[32] , message[100] , buffer[1500];
	int sock , read_size , total_size = 0;
	struct sockaddr_in dest;

	sock = socket(AF_INET , SOCK_STREAM , IPPROTO_TCP);

    //Prepare connection structures :)
    memset( &amp;dest , 0 , sizeof(dest) );
    dest.sin_family = AF_INET;

	printf(&quot;\nResolving %s...&quot; , server);
	if(hostname_to_ip(server , ip))
	{
		printf(&quot;Failed&quot;);
		return 1;
	}
	printf(&quot;%s&quot; , ip);
	dest.sin_addr.s_addr = inet_addr( ip );
	dest.sin_port = htons( 43 );

	//Now connect to remote server
	if(connect( sock , (const struct sockaddr*) &amp;dest , sizeof(dest) ) &lt; 0)
	{
		perror(&quot;connect failed&quot;);
	}

	//Now send some data or message
	printf(&quot;\nQuerying for ... %s ...&quot; , query);
	sprintf(message , &quot;%s\r\n&quot; , query);
	if( send(sock , message , strlen(message) , 0) &lt; 0)
	{
		perror(&quot;send failed&quot;);
	}

	//Now receive the response
	while( (read_size = recv(sock , buffer , sizeof(buffer) , 0) ) )
	{
		*response = realloc(*response , read_size + total_size);
		if(*response == NULL)
		{
			printf(&quot;realloc failed&quot;);
		}
		memcpy(*response + total_size , buffer , read_size);
		total_size += read_size;
	}
	printf(&quot;Done&quot;);
	fflush(stdout);

	*response = realloc(*response , total_size + 1);
	*(*response + total_size) = '&#92;&#48;';

	close(sock);
	return 0;
}

/*
 * @brief
 * Get the ip address of a given hostname
 *
 * */
int hostname_to_ip(char * hostname , char* ip)
{
	struct hostent *he;
	struct in_addr **addr_list;
	int i;

	if ( (he = gethostbyname( hostname ) ) == NULL)
	{
		// get the host info
		herror(&quot;gethostbyname&quot;);
		return 1;
	}

	addr_list = (struct in_addr **) he-&gt;h_addr_list;

	for(i = 0; addr_list[i] != NULL; i++)
	{
		//Return the first one;
		strcpy(ip , inet_ntoa(*addr_list[i]) );
		return 0;
	}

	return 0;
}

/*
 * Search and replace a string with another string , in a string
 * */
char *str_replace(char *search , char *replace , char *subject)
{
	char  *p = NULL , *old = NULL , *new_subject = NULL ;
	int c = 0 , search_size;

	search_size = strlen(search);

	//Count how many occurences
	for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search))
	{
		c++;
	}

	//Final size
	c = ( strlen(replace) - search_size )*c + strlen(subject);

	//New subject with new size
	new_subject = malloc( c );

	//Set it to blank
	strcpy(new_subject , &quot;&quot;);

	//The start position
	old = subject;

	for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search))
	{
		//move ahead and copy some text from original subject , from a certain position
		strncpy(new_subject + strlen(new_subject) , old , p - old);

		//move ahead and copy the replacement text
		strcpy(new_subject + strlen(new_subject) , replace);

		//The new start position after this search match
		old = p + search_size;
	}

	//Copy the part after the last search match
	strcpy(new_subject + strlen(new_subject) , old);

	return new_subject;
}
</pre>
<p>hostname_to_ip &#8211; This is a simple function to get an IP of a domain.<br />
str_replace &#8211; This is a generic string processing function that is used to search for a string in another big string and replace it with another string.</p>
<p><strong>Output</strong></p>
<pre class="brush: bash; title: Code; notranslate">
Enter domain name to whois : www.wikipedia.org

Resolving whois.iana.org...192.0.47.59
Querying for ... org ...Done
TLD Whois server is : whois.pir.org
Resolving whois.pir.org...149.17.192.7
Querying for ... wikipedia.org ...DoneAccess to .ORG WHOIS information is provided to assist persons in
determining the contents of a domain name registration record in the
Public Interest Registry registry database. The data in this record is provided by
Public Interest Registry for informational purposes only, and Public Interest Registry does not
guarantee its accuracy.  This service is intended only for query-based
access. You agree that you will use this data only for lawful purposes
and that, under no circumstances will you use this data to: (a) allow,
enable, or otherwise support the transmission by e-mail, telephone, or
facsimile of mass unsolicited, commercial advertising or solicitations
to entities other than the data recipient's own existing customers; or
(b) enable high volume, automated, electronic processes that send
queries or data to the systems of Registry Operator, a Registrar, or
Afilias except as reasonably necessary to register domain names or
modify existing registrations. All rights reserved. Public Interest Registry reserves
the right to modify these terms at any time. By submitting this query,
you agree to abide by this policy. 

Domain ID:D51687756-LROR
Domain Name:WIKIPEDIA.ORG
Created On:13-Jan-2001 00:12:14 UTC
Last Updated On:02-Dec-2009 20:57:17 UTC
Expiration Date:13-Jan-2015 00:12:14 UTC
Sponsoring Registrar:GoDaddy.com, Inc. (R91-LROR)
Status:CLIENT DELETE PROHIBITED
Status:CLIENT RENEW PROHIBITED
Status:CLIENT TRANSFER PROHIBITED
Status:CLIENT UPDATE PROHIBITED
Registrant ID:CR31094073
Registrant Name:DNS Admin
Registrant Organization:Wikimedia Foundation, Inc.
Registrant Street1:149 New Montgomery Street
Registrant Street2:Third Floor
Registrant Street3:
Registrant City:San Francisco
Registrant State/Province:California
Registrant Postal Code:94105
Registrant Country:US
Registrant Phone:+1.4158396885
Registrant Phone Ext.:
Registrant FAX:+1.4158820495
Registrant FAX Ext.:
Registrant Email:dns-admin@wikimedia.org
Admin ID:CR31094075
Admin Name:DNS Admin
Admin Organization:Wikimedia Foundation, Inc.
Admin Street1:149 New Montgomery Street
Admin Street2:Third Floor
Admin Street3:
Admin City:San Francisco
Admin State/Province:California
Admin Postal Code:94105
Admin Country:US
Admin Phone:+1.4158396885
Admin Phone Ext.:
Admin FAX:+1.4158820495
Admin FAX Ext.:
Admin Email:dns-admin@wikimedia.org
Tech ID:CR31094074
Tech Name:DNS Admin
Tech Organization:Wikimedia Foundation, Inc.
Tech Street1:149 New Montgomery Street
Tech Street2:Third Floor
Tech Street3:
Tech City:San Francisco
Tech State/Province:California
Tech Postal Code:94105
Tech Country:US
Tech Phone:+1.4158396885
Tech Phone Ext.:
Tech FAX:+1.4158820495
Tech FAX Ext.:
Tech Email:dns-admin@wikimedia.org
Name Server:NS0.WIKIMEDIA.ORG
Name Server:NS1.WIKIMEDIA.ORG
Name Server:NS2.WIKIMEDIA.ORG
Name Server:
Name Server:
Name Server:
Name Server:
Name Server:
Name Server:
Name Server:
Name Server:
Name Server:
Name Server:
DNSSEC:Unsigned
</pre>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1266&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/whois-client-code-in-c-with-linux-sockets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get local ip in C on linux</title>
		<link>http://www.binarytides.com/blog/get-local-ip-in-c-on-linux/</link>
		<comments>http://www.binarytides.com/blog/get-local-ip-in-c-on-linux/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 06:41:04 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[c]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1248</guid>
		<description><![CDATA[The local ip is the source ip in IP packets send out from a system. The kernal maintains routing tables which it uses to decide the default gateway , its interface and the local ip configured for that interface. The /proc/net/route file (not really a file but appears like one) has more information about it. A typical /proc/net/route output would look like : The above lists the interface , destination , gateway etc. The interface [...]]]></description>
			<content:encoded><![CDATA[<p>The local ip is the source ip in IP packets send out from a system. The kernal maintains routing tables which it uses to decide the default gateway , its interface and the local ip configured for that interface. The <em>/proc/net/route</em> file (not really a file but appears like one) has more information about it.</p>
<p>A typical <em>/proc/net/route</em> output would look like :</p>
<pre class="brush: bash; title: Code; notranslate">
$ cat /proc/net/route
Iface   Destination     Gateway         Flags   RefCnt  Use     Metric  Mask            MTU     Window  IRTT
eth0    0000A8C0        00000000        0001    0       0       1       00FFFFFF        0       0       0
eth0    0000FEA9        00000000        0001    0       0       1000    0000FFFF        0       0       0
eth0    00000000        0100A8C0        0003    0       0       0       00000000        0       0       0
</pre>
<p>The above lists the interface , destination , gateway etc. The interface (Iface) whose destination is 00000000 is the interface of the default gateway.</p>
<p>Now have a look at the route command output</p>
<pre class="brush: bash; title: Code; notranslate">
$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.0.0     0.0.0.0         255.255.255.0   U     1      0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 eth0
0.0.0.0         192.168.0.1     0.0.0.0         UG    0      0        0 eth0
</pre>
<p>Now the gateway for the destination 0.0.0.0 is the default gateway. So from the /proc/net/route output this line is of interest :</p>
<pre class="brush: bash; title: Code; notranslate">
eth0    00000000        0100A8C0        0003    0       0       0       00000000        0       0       0
</pre>
<p>Its destination is 00000000 and gateway is 0100A8C0. The gateway is actually the IP address of the gateway in hex format in reverse order (little endian). Its 01.00.A8.C0 or 1.0.168.192</p>
<p>So by reading that line in a C program we can find out the default gateway and its interface. The IP address of this interface shall be the source ip in IP packets send out from this system.</p>
<p>The code for this is pretty simple as we can see :</p>
<pre class="brush: cpp; title: Code; notranslate">

FILE *f;
char line[100] , *p , *c;

f = fopen(&quot;/proc/net/route&quot; , &quot;r&quot;);

while(fgets(line , 100 , f))
{
	p = strtok(line , &quot; \t&quot;);
	c = strtok(NULL , &quot; \t&quot;);

	if(p!=NULL &amp;&amp; c!=NULL)
	{
		if(strcmp(c , &quot;00000000&quot;) == 0)
		{
			printf(&quot;Default interface is : %s \n&quot; , p);
			break;
		}
	}
}
</pre>
<p>The above code prints : &#8220;Default interface is : eth0&#8243;</p>
<p>Now we need to get the ip address of the default interface eth0. The getnameinfo function can be used for this.<br />
Sample code is found <a target="_blank" href="http://www.kernel.org/doc/man-pages/online/pages/man3/getifaddrs.3.html" >here</a>.</p>
<p>Combining that with our previous code we get :</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
 * Find local ip used as source ip in ip packets.
 * Read the /proc/net/route file
 */

#include&lt;stdio.h&gt;	//printf
#include&lt;string.h&gt;	//memset
#include&lt;errno.h&gt;	//errno
#include&lt;sys/socket.h&gt;
#include&lt;netdb.h&gt;
#include&lt;ifaddrs.h&gt;
#include&lt;stdlib.h&gt;
#include&lt;unistd.h&gt;

int main ( int argc , char *argv[] )
{
    FILE *f;
    char line[100] , *p , *c;

    f = fopen(&quot;/proc/net/route&quot; , &quot;r&quot;);

    while(fgets(line , 100 , f))
    {
		p = strtok(line , &quot; \t&quot;);
		c = strtok(NULL , &quot; \t&quot;);

		if(p!=NULL &amp;&amp; c!=NULL)
		{
			if(strcmp(c , &quot;00000000&quot;) == 0)
			{
				printf(&quot;Default interface is : %s \n&quot; , p);
				break;
			}
		}
	}

    //which family do we require , AF_INET or AF_INET6
    int fm = AF_INET;
    struct ifaddrs *ifaddr, *ifa;
	int family , s;
	char host[NI_MAXHOST];

	if (getifaddrs(&amp;ifaddr) == -1)
	{
		perror(&quot;getifaddrs&quot;);
		exit(EXIT_FAILURE);
	}

	//Walk through linked list, maintaining head pointer so we can free list later
	for (ifa = ifaddr; ifa != NULL; ifa = ifa-&gt;ifa_next)
	{
		if (ifa-&gt;ifa_addr == NULL)
		{
			continue;
		}

		family = ifa-&gt;ifa_addr-&gt;sa_family;

		if(strcmp( ifa-&gt;ifa_name , p) == 0)
		{
			if (family == fm)
			{
				s = getnameinfo( ifa-&gt;ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6) , host , NI_MAXHOST , NULL , 0 , NI_NUMERICHOST);

				if (s != 0)
				{
					printf(&quot;getnameinfo() failed: %s\n&quot;, gai_strerror(s));
					exit(EXIT_FAILURE);
				}

				printf(&quot;address: %s&quot;, host);
			}
			printf(&quot;\n&quot;);
		}
	}

	freeifaddrs(ifaddr);

	return 0;
}
</pre>
<p><strong>Output</strong></p>
<pre class="brush: bash; title: Code; notranslate">
Default interface is : eth0 

address: 192.168.0.6
</pre>
<p>Another method is to open a connection to a remote server and call getsockname</p>
<p><strong>Code</strong></p>
<pre class="brush: cpp; title: Code; notranslate">
/*
 * Find local ip used as source ip in ip packets.
 * Use getsockname and a udp connection
 */

#include&lt;stdio.h&gt;	//printf
#include&lt;string.h&gt;	//memset
#include&lt;errno.h&gt;	//errno
#include&lt;sys/socket.h&gt;	//socket
#include&lt;netinet/in.h&gt; //sockaddr_in
#include&lt;arpa/inet.h&gt;	//getsockname
#include&lt;unistd.h&gt;	//close

int main ( int argc , char *argv[] )
{
    const char* google_dns_server = &quot;8.8.8.8&quot;;
    int dns_port = 53;

	struct sockaddr_in serv;

    int sock = socket ( AF_INET, SOCK_DGRAM, 0);

    //Socket could not be created
    if(sock &lt; 0)
    {
		perror(&quot;Socket error&quot;);
	}

	memset( &amp;serv, 0, sizeof(serv) );
    serv.sin_family = AF_INET;
    serv.sin_addr.s_addr = inet_addr( google_dns_server );
    serv.sin_port = htons( dns_port );

    int err = connect( sock , (const struct sockaddr*) &amp;serv , sizeof(serv) );

    struct sockaddr_in name;
    socklen_t namelen = sizeof(name);
    err = getsockname(sock, (struct sockaddr*) &amp;name, &amp;namelen);

	char buffer[100];
    const char* p = inet_ntop(AF_INET, &amp;name.sin_addr, buffer, 100);

	if(p != NULL)
	{
		printf(&quot;Local ip is : %s \n&quot; , buffer);
	}
	else
	{
		//Some error
		printf (&quot;Error number : %d . Error message : %s \n&quot; , errno , strerror(errno));
	}

    close(sock);

    return 0;
}
</pre>
<p><strong>Output</strong></p>
<pre class="brush: bash; title: Code; notranslate">
Local ip is : 192.168.0.6
</pre>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1248&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/get-local-ip-in-c-on-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code a packet sniffer in C with winpcap</title>
		<link>http://www.binarytides.com/blog/code-a-packet-sniffer-in-c-with-winpcap/</link>
		<comments>http://www.binarytides.com/blog/code-a-packet-sniffer-in-c-with-winpcap/#comments</comments>
		<pubDate>Sun, 18 Dec 2011 11:15:43 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[winpcap]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1244</guid>
		<description><![CDATA[Winpcap is a packet capture library for Windows used for packet sniffing and sending raw packets. Wireshark is a popular sniffer tool that uses winpcap to sniff packets. Here is a sample code which shows how winpcap can be used to sniff incoming packets on a particular interface. Code Compile The code can be compiled in Vc++ 2010 Express Edition Winpcap development files are needed for pcap.h/pcap.lib and other files. Create a project in VC++ [...]]]></description>
			<content:encoded><![CDATA[<p>Winpcap is a packet capture library for Windows used for packet sniffing and sending raw packets. Wireshark is a popular sniffer tool that uses winpcap to sniff packets.</p>
<p>Here is a sample code which shows how winpcap can be used to sniff incoming packets on a particular interface.</p>
<p><strong>Code</strong></p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Simple Sniffer with winpcap , prints ethernet , ip , tcp , udp and icmp headers along with data dump in hex
	Author : Silver Moon ( m00n.silv3r@gmail.com )
*/

#include &quot;stdio.h&quot;
#include &quot;winsock2.h&quot;	//need winsock for inet_ntoa and ntohs methods

#define HAVE_REMOTE
#include &quot;pcap.h&quot;	//Winpcap :)

#pragma comment(lib , &quot;ws2_32.lib&quot;) //For winsock
#pragma comment(lib , &quot;wpcap.lib&quot;) //For winpcap

//some packet processing functions
void ProcessPacket (u_char* , int); //This will decide how to digest

void print_ethernet_header (u_char*);
void PrintIpHeader (u_char* , int);
void PrintIcmpPacket (u_char* , int);
void print_udp_packet (u_char* , int);
void PrintTcpPacket (u_char* , int);
void PrintData (u_char* , int);

// Set the packing to a 1 byte boundary
//#include &quot;pshpack1.h&quot;
//Ethernet Header
typedef struct ethernet_header
{
	UCHAR dest[6];
	UCHAR source[6];
	USHORT type;
}   ETHER_HDR , *PETHER_HDR , FAR * LPETHER_HDR , ETHERHeader;

//Ip header (v4)
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;

//UDP header
typedef struct udp_hdr
{
	unsigned short source_port; // Source port no.
	unsigned short dest_port; // Dest. port no.
	unsigned short udp_length; // Udp packet length
	unsigned short udp_checksum; // Udp checksum (optional)
} UDP_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;

typedef struct icmp_hdr
{
	BYTE type; // ICMP Error type
	BYTE code; // Type sub code
	USHORT checksum;
	USHORT id;
	USHORT seq;
} ICMP_HDR;
// Restore the byte boundary back to the previous value
//#include &lt;poppack.h&gt;

FILE *logfile;
int tcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;
struct sockaddr_in source,dest;
char hex[2];

//Its free!
ETHER_HDR *ethhdr;
IPV4_HDR *iphdr;
TCP_HDR *tcpheader;
UDP_HDR *udpheader;
ICMP_HDR *icmpheader;
u_char *data;

int main()
{
	u_int i, res , inum ;
	u_char errbuf[PCAP_ERRBUF_SIZE] , buffer[100];
	u_char *pkt_data;
	time_t seconds;
	struct tm tbreak;
	pcap_if_t *alldevs, *d;
	pcap_t *fp;
	struct pcap_pkthdr *header;

	fopen_s(&amp;logfile , &quot;log.txt&quot; , &quot;w&quot;);

	if(logfile == NULL)
	{
		printf(&quot;Unable to create file.&quot;);
	}

	/* The user didn't provide a packet source: Retrieve the local device list */
    if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &amp;alldevs, errbuf) == -1)
    {
        fprintf(stderr,&quot;Error in pcap_findalldevs_ex: %s\n&quot;, errbuf);
        return -1;
    }

	i = 0;
    /* Print the list */
    for(d=alldevs; d; d=d-&gt;next)
    {
        printf(&quot;%d. %s\n    &quot;, ++i, d-&gt;name);

        if (d-&gt;description)
		{
            printf(&quot; (%s)\n&quot;, d-&gt;description);
		}
        else
		{
            printf(&quot; (No description available)\n&quot;);
		}
    }

    if (i==0)
    {
        fprintf(stderr,&quot;No interfaces found! Exiting.\n&quot;);
        return -1;
    }

	printf(&quot;Enter the interface number you would like to sniff : &quot;);
	scanf_s(&quot;%d&quot; , &amp;inum);

	/* Jump to the selected adapter */
    for (d=alldevs, i=0; i&lt; inum-1 ;d=d-&gt;next, i++);

    /* Open the device */
    if ( (fp= pcap_open(d-&gt;name,
                        100 /*snaplen*/,
                        PCAP_OPENFLAG_PROMISCUOUS /*flags*/,
                        20 /*read timeout*/,
                        NULL /* remote authentication */,
                        errbuf)
                        ) == NULL)
    {
        fprintf(stderr,&quot;\nError opening adapter\n&quot;);
        return -1;
    }

	//read packets in a loop :)
    while((res = pcap_next_ex( fp, &amp;header, &amp;pkt_data)) &gt;= 0)
    {
        if(res == 0)
		{
            // Timeout elapsed
            continue;
		}
		seconds = header-&gt;ts.tv_sec;
		localtime_s( &amp;tbreak , &amp;seconds);
		strftime (buffer , 80 , &quot;%d-%b-%Y %I:%M:%S %p&quot; , &amp;tbreak );
        //print pkt timestamp and pkt len
        //fprintf(logfile , &quot;\nNext Packet : %ld:%ld (Packet Length : %ld bytes) &quot; , header-&gt;ts.tv_sec, header-&gt;ts.tv_usec, header-&gt;len);
		fprintf(logfile , &quot;\nNext Packet : %s.%ld (Packet Length : %ld bytes) &quot; , buffer , header-&gt;ts.tv_usec, header-&gt;len);
		ProcessPacket(pkt_data , header-&gt;caplen);
    }

	if(res == -1)
    {
        fprintf(stderr, &quot;Error reading the packets: %s\n&quot; , pcap_geterr(fp) );
        return -1;
    }

	return 0;
}

void ProcessPacket(u_char* Buffer, int Size)
{
	//Ethernet header
	ethhdr = (ETHER_HDR *)Buffer;
	++total;

	//Ip packets
	if(ntohs(ethhdr-&gt;type) == 0x0800)
	{
		//ip header
		iphdr = (IPV4_HDR *)(Buffer + sizeof(ETHER_HDR));

		switch (iphdr-&gt;ip_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++;
			PrintTcpPacket(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);
}

/*
	Print the Ethernet header
*/
void print_ethernet_header (u_char* buffer )
{
	ETHER_HDR *eth = (ETHER_HDR *)buffer;

	fprintf(logfile,&quot;\n&quot;);
	fprintf(logfile,&quot;Ethernet Header\n&quot;);
	fprintf(logfile , &quot; |-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n&quot;, eth-&gt;dest[0] , eth-&gt;dest[1] , eth-&gt;dest[2] , eth-&gt;dest[3] , eth-&gt;dest[4] , eth-&gt;dest[5] );
    fprintf(logfile , &quot; |-Source Address      : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n&quot;, eth-&gt;source[0] , eth-&gt;source[1] , eth-&gt;source[2] , eth-&gt;source[3] , eth-&gt;source[4] , eth-&gt;source[5] );
    fprintf(logfile , &quot; |-Protocol            : 0x%.4x \n&quot; , ntohs(eth-&gt;type) );
}

/*
	Print the IP header for IP packets
*/
void PrintIpHeader (unsigned char* Buffer, int Size)
{
	int iphdrlen = 0;

	iphdr = (IPV4_HDR *)(Buffer + sizeof(ETHER_HDR));
	iphdrlen = iphdr-&gt;ip_header_len*4;

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

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

	print_ethernet_header(Buffer);

	fprintf(logfile,&quot;\n&quot;);
	fprintf(logfile,&quot;IP Header\n&quot;);
	fprintf(logfile,&quot; |-IP Version : %d\n&quot;,(unsigned int)iphdr-&gt;ip_version);
	fprintf(logfile,&quot; |-IP Header Length : %d DWORDS or %d Bytes\n&quot;,(unsigned int)iphdr-&gt;ip_header_len,((unsigned int)(iphdr-&gt;ip_header_len))*4);
	fprintf(logfile,&quot; |-Type Of Service : %d\n&quot;,(unsigned int)iphdr-&gt;ip_tos);
	fprintf(logfile,&quot; |-IP Total Length : %d Bytes(Size of Packet)\n&quot;,ntohs(iphdr-&gt;ip_total_length));
	fprintf(logfile,&quot; |-Identification : %d\n&quot;,ntohs(iphdr-&gt;ip_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)iphdr-&gt;ip_ttl);
	fprintf(logfile,&quot; |-Protocol : %d\n&quot;,(unsigned int)iphdr-&gt;ip_protocol);
	fprintf(logfile,&quot; |-Checksum : %d\n&quot;,ntohs(iphdr-&gt;ip_checksum));
	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));
}

/*
	Print the TCP header for TCP packets
*/
void PrintTcpPacket(u_char* Buffer, int Size)
{
	unsigned short iphdrlen;
	int header_size = 0 , tcphdrlen , data_size;

	iphdr = (IPV4_HDR *)(Buffer + sizeof(ETHER_HDR));
	iphdrlen = iphdr-&gt;ip_header_len*4;

	tcpheader = (TCP_HDR*)( Buffer + iphdrlen + sizeof(ETHER_HDR) );
	tcphdrlen = tcpheader-&gt;data_offset*4;

	data = ( Buffer + sizeof(ETHER_HDR) + iphdrlen + tcphdrlen );
	data_size = (Size - sizeof(ETHER_HDR) - iphdrlen - tcphdrlen );

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

	PrintIpHeader(Buffer,Size);

	fprintf(logfile,&quot;\n&quot;);
	fprintf(logfile,&quot;TCP Header\n&quot;);
	fprintf(logfile,&quot; |-Source Port : %u\n&quot;,ntohs(tcpheader-&gt;source_port));
	fprintf(logfile,&quot; |-Destination Port : %u\n&quot;,ntohs(tcpheader-&gt;dest_port));
	fprintf(logfile,&quot; |-Sequence Number : %u\n&quot;,ntohl(tcpheader-&gt;sequence));
	fprintf(logfile,&quot; |-Acknowledge Number : %u\n&quot;,ntohl(tcpheader-&gt;acknowledge));
	fprintf(logfile,&quot; |-Header Length : %d DWORDS or %d BYTES\n&quot; , (unsigned int)tcpheader-&gt;data_offset,(unsigned int)tcpheader-&gt;data_offset*4);
	fprintf(logfile,&quot; |-CWR Flag : %d\n&quot;,(unsigned int)tcpheader-&gt;cwr);
	fprintf(logfile,&quot; |-ECN Flag : %d\n&quot;,(unsigned int)tcpheader-&gt;ecn);
	fprintf(logfile,&quot; |-Urgent Flag : %d\n&quot;,(unsigned int)tcpheader-&gt;urg);
	fprintf(logfile,&quot; |-Acknowledgement Flag : %d\n&quot;,(unsigned int)tcpheader-&gt;ack);
	fprintf(logfile,&quot; |-Push Flag : %d\n&quot;,(unsigned int)tcpheader-&gt;psh);
	fprintf(logfile,&quot; |-Reset Flag : %d\n&quot;,(unsigned int)tcpheader-&gt;rst);
	fprintf(logfile,&quot; |-Synchronise Flag : %d\n&quot;,(unsigned int)tcpheader-&gt;syn);
	fprintf(logfile,&quot; |-Finish Flag : %d\n&quot;,(unsigned int)tcpheader-&gt;fin);
	fprintf(logfile,&quot; |-Window : %d\n&quot;,ntohs(tcpheader-&gt;window));
	fprintf(logfile,&quot; |-Checksum : %d\n&quot;,ntohs(tcpheader-&gt;checksum));
	fprintf(logfile,&quot; |-Urgent Pointer : %d\n&quot;,tcpheader-&gt;urgent_pointer);
	fprintf(logfile,&quot;\n&quot;);
	fprintf(logfile,&quot; DATA Dump &quot;);
	fprintf(logfile,&quot;\n&quot;);

	fprintf(logfile,&quot;IP Header\n&quot;);
	PrintData( (u_char*)iphdr , iphdrlen);

	fprintf(logfile,&quot;TCP Header\n&quot;);
	PrintData( (u_char*)tcpheader , tcphdrlen );

	fprintf(logfile,&quot;Data Payload\n&quot;);
	PrintData( data , data_size );

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

/*
	Print the UDP header for UDP packets
*/
void print_udp_packet(u_char *Buffer,int Size)
{
	int iphdrlen = 0 , data_size = 0;

	iphdr = (IPV4_HDR *)(Buffer + sizeof(ETHER_HDR));
	iphdrlen = iphdr-&gt;ip_header_len*4;

	udpheader = (UDP_HDR*)( Buffer + iphdrlen + sizeof(ETHER_HDR) );

	data = ( Buffer + sizeof(ETHER_HDR) + iphdrlen + sizeof(UDP_HDR) );
	data_size = (Size - sizeof(ETHER_HDR) - iphdrlen - sizeof(UDP_HDR) );

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

	PrintIpHeader(Buffer,Size);

	fprintf(logfile,&quot;\nUDP Header\n&quot;);
	fprintf(logfile,&quot; |-Source Port : %d\n&quot;,ntohs(udpheader-&gt;source_port));
	fprintf(logfile,&quot; |-Destination Port : %d\n&quot;,ntohs(udpheader-&gt;dest_port));
	fprintf(logfile,&quot; |-UDP Length : %d\n&quot;,ntohs(udpheader-&gt;udp_length));
	fprintf(logfile,&quot; |-UDP Checksum : %d\n&quot;,ntohs(udpheader-&gt;udp_checksum));

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

	fprintf(logfile,&quot;IP Header\n&quot;);
	PrintData( (u_char*)iphdr , iphdrlen);

	fprintf(logfile,&quot;UDP Header\n&quot;);
	PrintData((u_char*)udpheader , sizeof(UDP_HDR));

	fprintf(logfile,&quot;Data Payload\n&quot;);
	PrintData(data ,data_size);

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

void PrintIcmpPacket(u_char* Buffer , int Size)
{
	int iphdrlen = 0 , icmphdrlen = 0 , data_size=0;

	iphdr = (IPV4_HDR *)(Buffer + sizeof(ETHER_HDR));
	iphdrlen = iphdr-&gt;ip_header_len*4;

	icmpheader = (ICMP_HDR*)( Buffer + iphdrlen + sizeof(ETHER_HDR) );

	data = ( Buffer + sizeof(ETHER_HDR) + iphdrlen + sizeof(ICMP_HDR) );
	data_size = (Size - sizeof(ETHER_HDR) - iphdrlen - sizeof(ICMP_HDR) );

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

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

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

	if((unsigned int)(icmpheader-&gt;type)==11)
	{
		fprintf(logfile,&quot; (TTL Expired)\n&quot;);
	}
	else if((unsigned int)(icmpheader-&gt;type)==0)
	{
		fprintf(logfile,&quot; (ICMP Echo Reply)\n&quot;);
	}

	fprintf(logfile,&quot; |-Code : %d\n&quot;,(unsigned int)(icmpheader-&gt;code));
	fprintf(logfile,&quot; |-Checksum : %d\n&quot;,ntohs(icmpheader-&gt;checksum));
	fprintf(logfile,&quot; |-ID : %d\n&quot;,ntohs(icmpheader-&gt;id));
	fprintf(logfile,&quot; |-Sequence : %d\n&quot;,ntohs(icmpheader-&gt;seq));
	fprintf(logfile,&quot;\n&quot;);

	fprintf(logfile , &quot;IP Header\n&quot;);
	PrintData( (u_char*)iphdr , iphdrlen);

	fprintf(logfile , &quot;ICMP Header\n&quot;);
	PrintData( (u_char*)icmpheader , sizeof(ICMP_HDR) );

	fprintf(logfile , &quot;Data Payload\n&quot;);
	PrintData(data , data_size);

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

/*
	Print the hex values of the data
*/
void PrintData (u_char* data , int Size)
{
	unsigned char a , line[17] , c;
	int j;

	//loop over each character and print
	for(i=0 ; i &lt; Size ; i++)
	{
		c = data[i];

		//Print the hex value for every character , with a space
		fprintf(logfile,&quot; %.2x&quot;, (unsigned int) c);

		//Add the character to data line
		a = ( c &gt;=32 &amp;&amp; c &lt;=128) ? (unsigned char) c : '.';

		line[i%16] = a;

		//if last character of a line , then print the line - 16 characters in 1 line
		if( (i!=0 &amp;&amp; (i+1)%16==0) || i == Size - 1)
		{
			line[i%16 + 1] = '&#92;&#48;';

			//print a big gap of 10 characters between hex and characters
			fprintf(logfile ,&quot;          &quot;);

			//Print additional spaces for last lines which might be less than 16 characters in length
			for( j = strlen(line) ; j &lt; 16; j++)
			{
				fprintf(logfile , &quot;   &quot;);
			}

			fprintf(logfile , &quot;%s \n&quot; , line);
		}
	}

	fprintf(logfile , &quot;\n&quot;);
}
</pre>
<p><strong>Compile</strong><br />
The code can be compiled in Vc++ 2010 Express Edition<br />
Winpcap development files are needed for pcap.h/pcap.lib and other files.</p>
<p>Create a project in VC++ and add a main.c file and put the source code inside it. Then in <em>Project > Properties (Alt + F7)</em> add the directory path of winpcap header and lib files.</p>
<p>Now Build and Run.</p>
<p><strong>Output</strong></p>
<p>The terminal will show the number of packets sniffed protocolwise.</p>
<pre class="brush: bash; title: Code; notranslate">
1. rpcap://\Device\NPF_{EA7C1F00-CD10-4288-8B0D-EBD63C22F468}
     (Network adapter 'Intel(R) 82566DC Gigabit Network Connection (Microsoft's
Packet Scheduler) ' on local host)
Enter the interface number you would like to sniff : 1
TCP : 327 UDP : 35 ICMP : 74 IGMP : 3 Others : 0 Total : 462
</pre>
<p>The log file will have more information. Headers would be broken down into individual fields and data would be shown in hex format.</p>
<pre class="brush: cpp; title: Code; notranslate">
Next Packet : 18-Dec-2011 04:35:17 PM.7759 (Packet Length : 432 bytes) 

***********************TCP Packet*************************

Ethernet Header
 |-Destination Address : 00-1E-58-B8-D4-69
 |-Source Address      : 00-1C-C0-F8-79-EE
 |-Protocol            : 0x0800 

IP Header
 |-IP Version : 4
 |-IP Header Length : 5 DWORDS or 20 Bytes
 |-Type Of Service : 0
 |-IP Total Length : 418 Bytes(Size of Packet)
 |-Identification : 11810
 |-Reserved ZERO Field : 0
 |-Dont Fragment Field : 1
 |-More Fragment Field : 0
 |-TTL : 128
 |-Protocol : 6
 |-Checksum : 1370
 |-Source IP : 192.168.0.101
 |-Destination IP : 96.17.164.187

TCP Header
 |-Source Port : 1211
 |-Destination Port : 80
 |-Sequence Number : 658049438
 |-Acknowledge Number : 3756530811
 |-Header Length : 5 DWORDS or 20 BYTES
 |-CWR Flag : 0
 |-ECN Flag : 0
 |-Urgent Flag : 0
 |-Acknowledgement Flag : 1
 |-Push Flag : 1
 |-Reset Flag : 0
 |-Synchronise Flag : 0
 |-Finish Flag : 0
 |-Window : 17520
 |-Checksum : 51054
 |-Urgent Pointer : 0

 DATA Dump
IP Header
 45 00 01 a2 2e 22 40 00 80 06 05 5a c0 a8 00 65          E....&quot;@.€..Z...e
 60 11 a4 bb                                              `... 

TCP Header
 04 bb 00 50 27 39 09 9e df e8 1c 7b 50 18 44 70          ...P'9.....{P.Dp
 c7 6e 00 00                                              .n.. 

Data Payload
 47 45 54 20 2f 31 2f 3f 42 57 31 33 6a 67 25 32          GET /1/?BW13jg%2
 42 56 52 48 35 6c 52 6c 55 25 32 42 37 71 63 4a          BVRH5lRlU%2B7qcJ
 30 44 78 6d 53 62 45 44 32 46 4d 43 76 59 74 43          0DxmSbED2FMCvYtC
 6b 58 6c 48 25 32 46 59 38 4a 41 41 41 41 41 41          kXlH%2FY8JAAAAAA
 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41          AAAAAAAAAAAAAAAA
 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41          AAAAAAAAAAAAAAAA
 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41          AAAAAAAAAAAAAAAA
 41 41 41 47 4e 74 5a 43 35 6c 65 47 55 41 56 32          AAAGNtZC5leGUAV2
 6c 75 5a 47 39 33 63 79 42 44 62 32 31 74 59 57          luZG93cyBDb21tYW
 35 6b 49 46 42 79 62 32 4e 6c 63 33 4e 76 63 67          5kIFByb2Nlc3Nvcg
 41 31 4c 6a 45 75 4d 6a 59 77 4d 43 34 31 4e 54          A1LjEuMjYwMC41NT
 45 79 41 45 31 70 59 33 4a 76 63 32 39 6d 64 43          EyAE1pY3Jvc29mdC
 42 44 62 33 4a 77 62 33 4a 68 64 47 6c 76 62 67          BDb3Jwb3JhdGlvbg
 41 41 41 41 25 33 44 25 33 44 20 48 54 54 50 2f          AAAA%3D%3D HTTP/
 31 2e 31 0d 0a 48 6f 73 74 3a 20 70 61 32 2e 7a          1.1..Host: pa2.z
 6f 6e 65 6c 61 62 73 2e 63 6f 6d 0d 0a 41 63 63          onelabs.com..Acc
 65 70 74 2d 45 6e 63 6f 64 69 6e 67 3a 20 67 7a          ept-Encoding: gz
 69 70 0d 0a 41 63 63 65 70 74 3a 20 2a 2f 2a 0d          ip..Accept: */*.
 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74          .Content-Type: t
 65 78 74 2f 70 6c 61 69 6e 0d 0a 55 73 65 72 2d          ext/plain..User-
 41 67 65 6e 74 3a 20 5a 6f 6e 65 41 6c 61 72 6d          Agent: ZoneAlarm
 2f 39 2e 31 2e 30 30 38 2e 30 30 30 20 28 6f 65          /9.1.008.000 (oe
 6d 2d 31 30 34 33 3b 20 65 6e 2d 55 53 29 20 5a          m-1043; en-US) Z
 53 50 2f 32 2e 32 0d 0a 0d 0a                            SP/2.2.... 

###########################################################
</pre>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1244&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/code-a-packet-sniffer-in-c-with-winpcap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get mac address from ip in winsock</title>
		<link>http://www.binarytides.com/blog/get-mac-address-from-ip-in-winsock/</link>
		<comments>http://www.binarytides.com/blog/get-mac-address-from-ip-in-winsock/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 09:55:06 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[winsock]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1235</guid>
		<description><![CDATA[Mac address or hardware address is a 48bit (6 character) wide address assigned to a network interface. It is important for the packet delivery between 2 devices like your computer and the router. Ethernet protocol uses the mac address to deliver it to the right network node. It looks like this 00-1E-58-B8-D4-69 ( the dash is not relevant). Mac address of any interface can also be changed ( called mac spoofing ) . Any network [...]]]></description>
			<content:encoded><![CDATA[<p>Mac address or hardware address is a 48bit (6 character) wide address assigned to a network interface. It is important for the packet delivery between 2 devices like your computer and the router. Ethernet protocol uses the mac address to deliver it to the right network node. It looks like this 00-1E-58-B8-D4-69 ( the dash is not relevant). Mac address of any interface can also be changed ( called mac spoofing ) .</p>
<p>Any network packet that needs to travel from a certain ip address to another needs to know the destination ip&#8217;s mac address. On windows there is a iphlpapi.dll file which has a function called SendARP which can be used to get the mac address of a given ip address.</p>
<p><strong>Code</strong></p>
<p>In <em>Vc++ 6.0</em> , where iphlpapi.h and iphlpapi.lib are not available , we can create necessary structures and pointers to functions inside iphlpapi.dll file and use them.</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
	Author: Silver Moon ( m00n.silv3r@gmail.com )

	Find mac address of a given IP address using iphlpapi
*/

#include &quot;winsock2.h&quot;
#include &quot;windows.h&quot;
#include &quot;time.h&quot;
#include &quot;stdio.h&quot;

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

#define MAX_ADAPTER_NAME_LENGTH 256
#define MAX_ADAPTER_DESCRIPTION_LENGTH 128
#define MAX_ADAPTER_ADDRESS_LENGTH 8

//Necessary Structs
typedef struct
{
	char String[4 * 4];
} IP_ADDRESS_STRING, *PIP_ADDRESS_STRING, IP_MASK_STRING, *PIP_MASK_STRING;

typedef struct _IP_ADDR_STRING
{
	struct _IP_ADDR_STRING* Next;
	IP_ADDRESS_STRING IpAddress;
	IP_MASK_STRING IpMask;
	DWORD Context;
} IP_ADDR_STRING , *PIP_ADDR_STRING;

typedef struct _IP_ADAPTER_INFO
{
    struct _IP_ADAPTER_INFO* Next;
    DWORD           ComboIndex;
    char            AdapterName[MAX_ADAPTER_NAME_LENGTH + 4];
    char            Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4];
    UINT            AddressLength;
    BYTE            Address[MAX_ADAPTER_ADDRESS_LENGTH];
    DWORD           Index;
    UINT            Type;
    UINT            DhcpEnabled;
    PIP_ADDR_STRING CurrentIpAddress;
    IP_ADDR_STRING  IpAddressList;
    IP_ADDR_STRING  GatewayList;
    IP_ADDR_STRING  DhcpServer;
    BOOL            HaveWins;
    IP_ADDR_STRING  PrimaryWinsServer;
    IP_ADDR_STRING  SecondaryWinsServer;
    time_t          LeaseObtained;
    time_t          LeaseExpires;
} IP_ADAPTER_INFO, *PIP_ADAPTER_INFO;

//Functions
void loadiphlpapi();
void GetMacAddress(unsigned char * , struct in_addr );

//Loads from Iphlpapi.dll
typedef DWORD (WINAPI* psendarp)(struct in_addr DestIP, struct in_addr SrcIP, PULONG pMacAddr, PULONG PhyAddrLen );
typedef DWORD (WINAPI* pgetadaptersinfo)(PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen );

int main()
{
	unsigned char mac[6];
	struct in_addr srcip;
	char ip_address[32];

	WSADATA firstsock;

	if (WSAStartup(MAKEWORD(2,2),&amp;firstsock) != 0)
	{
		printf(&quot;\nFailed to initialise winsock.&quot;);
		printf(&quot;\nError Code : %d&quot;,WSAGetLastError());
		return 1;	//Return 1 on error
	}

	loadiphlpapi();

	//Ask user to select the device he wants to use
	printf(&quot;Enter the ip address : &quot;);
	scanf(&quot;%s&quot;,ip_address);
	srcip.s_addr = inet_addr(ip_address);

	//Get mac addresses of the ip
	GetMacAddress(mac , srcip);
	printf(&quot;Selected device has mac address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X&quot;,mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
	printf(&quot;\n&quot;);

	return 0;
}

//2 functions
psendarp SendArp;
pgetadaptersinfo GetAdaptersInfo;

void loadiphlpapi()
{
	HINSTANCE hDll = LoadLibrary(&quot;iphlpapi.dll&quot;);

	GetAdaptersInfo = (pgetadaptersinfo)GetProcAddress(hDll,&quot;GetAdaptersInfo&quot;);
	if(GetAdaptersInfo==NULL)
	{
		printf(&quot;Error in iphlpapi.dll%d&quot;,GetLastError());
	}

	SendArp = (psendarp)GetProcAddress(hDll,&quot;SendARP&quot;);

	if(SendArp==NULL)
	{
		printf(&quot;Error in iphlpapi.dll%d&quot;,GetLastError());
	}
}

/*
	Get the mac address of a given ip
*/
void GetMacAddress(unsigned char *mac , struct in_addr destip)
{
	DWORD ret;
	struct in_addr srcip;
	ULONG MacAddr[2];
	ULONG PhyAddrLen = 6;  /* default to length of six bytes */
	int i;

	srcip.s_addr=0;

	//Send an arp packet
	ret = SendArp(destip , srcip , MacAddr , &amp;PhyAddrLen);

	//Prepare the mac address
	if(PhyAddrLen)
	{
		BYTE *bMacAddr = (BYTE *) &amp; MacAddr;
		for (i = 0; i &lt; (int) PhyAddrLen; i++)
		{
			mac[i] = (char)bMacAddr[i];
		}
	}
}
</pre>
<p><strong>Output</strong></p>
<pre class="brush: bash; title: Code; notranslate">
Enter the ip address : 192.168.0.1
Selected device has mac address : 00-1E-58-B8-D4-69
Press any key to continue
</pre>
<p>On <em>Visual C++ 2010 Express Edition</em> , the iphlpapi.lib and iphlpapi.h files are available so the code is much simpler and shorter.</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
Author: Silver Moon ( m00n.silv3r@gmail.com )
Find mac address of a given IP address using iphlpapi
*/

#include &quot;winsock2.h&quot;
#include &quot;iphlpapi.h&quot;	//For SendARP
#include &quot;stdio.h&quot;
#include &quot;conio.h&quot;

#pragma comment(lib , &quot;iphlpapi.lib&quot;) //For iphlpapi
#pragma comment(lib , &quot;ws2_32.lib&quot;) //For winsock

void GetMacAddress(unsigned char * , struct in_addr );

int main()
{
	unsigned char mac[6];
	struct in_addr srcip;
	char ip_address[32];

	WSADATA firstsock;

	if (WSAStartup(MAKEWORD(2,2),&amp;firstsock) != 0)
	{
		printf(&quot;\nFailed to initialise winsock.&quot;);
		printf(&quot;\nError Code : %d&quot; , WSAGetLastError() );
		return 1;
	}

	//Ask user to select the device he wants to use
	printf(&quot;Enter the ip address : &quot;);
	scanf_s(&quot;%s&quot;,ip_address);
	srcip.s_addr = inet_addr(ip_address);

	//Get mac addresses of the ip
	GetMacAddress(mac , srcip);
	printf(&quot;Selected device has mac address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X&quot;,mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
	printf(&quot;\n&quot;);

	_getch();
	return 0;
}

/*
	Get the mac address of a given ip
*/
void GetMacAddress(unsigned char *mac , struct in_addr destip)
{
	DWORD ret;
	IPAddr srcip;
	ULONG MacAddr[2];
	ULONG PhyAddrLen = 6;  /* default to length of six bytes */
	int i;

	srcip = 0;

	//Send an arp packet
	ret = SendARP((IPAddr) destip.S_un.S_addr , srcip , MacAddr , &amp;PhyAddrLen);

	//Prepare the mac address
	if(PhyAddrLen)
	{
		BYTE *bMacAddr = (BYTE *) &amp; MacAddr;
		for (i = 0; i &lt; (int) PhyAddrLen; i++)
		{
			mac[i] = (char)bMacAddr[i];
		}
	}
}
</pre>
<p><strong>Output</strong></p>
<pre class="brush: bash; title: Code; notranslate">
Enter the ip address : 192.168.0.101
Selected device has mac address : 00-1C-C0-F8-79-EE
</pre>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1235&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/get-mac-address-from-ip-in-winsock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get ip address from hostname in C using Linux sockets</title>
		<link>http://www.binarytides.com/blog/get-ip-address-from-hostname-in-c-using-linux-sockets/</link>
		<comments>http://www.binarytides.com/blog/get-ip-address-from-hostname-in-c-using-linux-sockets/#comments</comments>
		<pubDate>Sat, 10 Dec 2011 15:17:55 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1194</guid>
		<description><![CDATA[Here are 2 methods to get the ip address of a hostname : The first method uses the traditional gethostbyname function to retrieve information about a hostname/domain name. Code Compile and Run The second method uses the getaddrinfo function to retrieve information about a hostname/domain name. Code Compile and Run]]></description>
			<content:encoded><![CDATA[<p>Here are 2 methods to get the ip address of a hostname :</p>
<p>The first method uses the traditional gethostbyname function to retrieve information about a hostname/domain name.<br />
<strong>Code</strong></p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt; //printf
#include&lt;string.h&gt; //memset
#include&lt;stdlib.h&gt; //for exit(0);
#include&lt;sys/socket.h&gt;
#include&lt;errno.h&gt; //For errno - the error number
#include&lt;netdb.h&gt;	//hostent
#include&lt;arpa/inet.h&gt;

int hostname_to_ip(char *  , char *);

int main(int argc , char *argv[])
{
	if(argc &lt;2)
	{
		printf(&quot;Please provide a hostname to resolve&quot;);
		exit(1);
	}

	char *hostname = argv[1];
	char ip[100];

	hostname_to_ip(hostname , ip);
	printf(&quot;%s resolved to %s&quot; , hostname , ip);

	printf(&quot;\n&quot;);

}
/*
	Get ip from domain name
 */

int hostname_to_ip(char * hostname , char* ip)
{
	struct hostent *he;
	struct in_addr **addr_list;
	int i;

	if ( (he = gethostbyname( hostname ) ) == NULL)
	{
		// get the host info
		herror(&quot;gethostbyname&quot;);
		return 1;
	}

	addr_list = (struct in_addr **) he-&gt;h_addr_list;

	for(i = 0; addr_list[i] != NULL; i++)
	{
		//Return the first one;
		strcpy(ip , inet_ntoa(*addr_list[i]) );
		return 0;
	}

	return 1;
}
</pre>
<p><strong>Compile and Run</strong></p>
<pre class="brush: bash; title: Code; notranslate">

$ gcc hostname_to_ip.c &amp;&amp; ./a.out www.google.com
www.google.com resolved to 74.125.235.16

$ gcc hostname_to_ip.c &amp;&amp; ./a.out www.msn.com
www.msn.com resolved to 207.46.140.34

$ gcc hostname_to_ip.c &amp;&amp; ./a.out www.yahoo.com
www.yahoo.com resolved to 98.137.149.56
</pre>
<p>The second method uses the getaddrinfo function to retrieve information about a hostname/domain name.<br />
<strong>Code</strong></p>
<pre class="brush: cpp; title: Code; notranslate">
#include&lt;stdio.h&gt; //printf
#include&lt;string.h&gt; //memset
#include&lt;stdlib.h&gt; //for exit(0);
#include&lt;sys/socket.h&gt;
#include&lt;errno.h&gt; //For errno - the error number
#include&lt;netdb.h&gt;	//hostent
#include&lt;arpa/inet.h&gt;

int hostname_to_ip(char *  , char *);

int main(int argc , char *argv[])
{
	if(argc &lt;2)
	{
		printf(&quot;Please provide a hostname to resolve&quot;);
		exit(1);
	}

	char *hostname = argv[1];
	char ip[100];

	hostname_to_ip(hostname , ip);
	printf(&quot;%s resolved to %s&quot; , hostname , ip);

	printf(&quot;\n&quot;);

}
/*
	Get ip from domain name
 */

int hostname_to_ip(char *hostname , char *ip)
{
	int sockfd;
	struct addrinfo hints, *servinfo, *p;
	struct sockaddr_in *h;
	int rv;

	memset(&amp;hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
	hints.ai_socktype = SOCK_STREAM;

	if ( (rv = getaddrinfo( hostname , &quot;http&quot; , &amp;hints , &amp;servinfo)) != 0)
	{
		fprintf(stderr, &quot;getaddrinfo: %s\n&quot;, gai_strerror(rv));
		return 1;
	}

	// loop through all the results and connect to the first we can
	for(p = servinfo; p != NULL; p = p-&gt;ai_next)
	{
		h = (struct sockaddr_in *) p-&gt;ai_addr;
		strcpy(ip , inet_ntoa( h-&gt;sin_addr ) );
	}

	freeaddrinfo(servinfo); // all done with this structure
	return 0;
}
</pre>
<p><strong>Compile and Run</strong></p>
<pre class="brush: bash; title: Code; notranslate">
$ gcc hostname_to_ip.c &amp;&amp; ./a.out www.google.com
www.google.com resolved to 74.125.235.19

$ gcc hostname_to_ip.c &amp;&amp; ./a.out www.yahoo.com
www.yahoo.com resolved to 72.30.2.43

$ gcc hostname_to_ip.c &amp;&amp; ./a.out www.msn.com
www.msn.com resolved to 207.46.140.34
</pre>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1194&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/get-ip-address-from-hostname-in-c-using-linux-sockets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Packet Sniffer Code in C using Linux Sockets (BSD) &#8211; Part 2</title>
		<link>http://www.binarytides.com/blog/packet-sniffer-code-in-c-using-linux-sockets-bsd-part-2/</link>
		<comments>http://www.binarytides.com/blog/packet-sniffer-code-in-c-using-linux-sockets-bsd-part-2/#comments</comments>
		<pubDate>Thu, 01 Dec 2011 12:27:46 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1045</guid>
		<description><![CDATA[In the previous part we made a simple sniffer which created a raw socket and started receiving on it. But it had few drawbacks : 1. Could sniff only incoming data. 2. Could sniff only TCP or UDP or ICMP or any one protocol packets at a time. 3. Provided IP frames , so ethernet headers were not available. In this article we are going to modify the same code to fix the above 3 [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.binarytides.com/blog/packet-sniffer-code-in-c-using-linux-sockets-bsd/" >previous part</a> we made a simple sniffer which created a raw socket and started receiving on it. But it had few drawbacks :</p>
<p>1. Could sniff only incoming data.<br />
2. Could sniff only TCP or UDP or ICMP or any one protocol packets at a time.<br />
3. Provided IP frames , so ethernet headers were not available.</p>
<p>In this article we are going to modify the same code to fix the above 3 drawbacks. However we shall not be using libpcap.<br />
This will be done using pure linux sockets.</p>
<p>The difference is very small and is 2 lines :<br />
Instead of :</p>
<pre class="brush: cpp; title: Code; notranslate">
sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
</pre>
<p>We do :</p>
<pre class="brush: cpp; title: Code; notranslate">
sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;
//Optional
//setsockopt(sock_raw , SOL_SOCKET , SO_BINDTODEVICE , &quot;eth0&quot; , strlen(&quot;eth0&quot;)+ 1 );
</pre>
<p>and we are done. Now it will :<br />
1. Sniff both incoming and outgoing traffic.<br />
2. Sniff ALL ETHERNET FRAMES , which includes all kinds of IP packets and even more if there are any.<br />
3. Provides the Ethernet headers too , which contain the mac addresses.</p>
<p>The setsockopt line is optional.<br />
Its important to provide the correct interface name to setsockopt , eth0 in this case and in most cases.<br />
So may be you would like to present the user with a list of interfaces available and allow him to choose the one to be sniffed.</p>
<p>Here is the full source code :</p>
<pre class="brush: cpp; title: Code; notranslate">

#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;stdlib.h&gt;	//malloc
#include&lt;string.h&gt;	//strlen

#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;netinet/if_ether.h&gt;	//For ETH_P_ALL
#include&lt;net/ethernet.h&gt;	//For ether_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_packet(unsigned char * , int );
void print_udp_packet(unsigned char * , int );
void print_icmp_packet(unsigned char* , int );
void PrintData (unsigned char* , int);

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

int main()
{
	int saddr_size , data_size;
	struct sockaddr saddr;

	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 log.txt file.&quot;);
	}
	printf(&quot;Starting...\n&quot;);

	int sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;
	//setsockopt(sock_raw , SOL_SOCKET , SO_BINDTODEVICE , &quot;eth0&quot; , strlen(&quot;eth0&quot;)+ 1 );

	if(sock_raw &lt; 0)
	{
		//Print the error with proper message
		perror(&quot;Socket Error&quot;);
		return 1;
	}
	while(1)
	{
		saddr_size = sizeof saddr;
		//Receive a packet
		data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &amp;saddr , (socklen_t*)&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 , excluding the ethernet header
	struct iphdr *iph = (struct iphdr*)(buffer + sizeof(struct ethhdr));
	++total;
	switch (iph-&gt;protocol) //Check the Protocol and do accordingly...
	{
		case 1:  //ICMP Protocol
			++icmp;
			print_icmp_packet( 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_ethernet_header(unsigned char* Buffer, int Size)
{
	struct ethhdr *eth = (struct ethhdr *)Buffer;

	fprintf(logfile , &quot;\n&quot;);
	fprintf(logfile , &quot;Ethernet Header\n&quot;);
	fprintf(logfile , &quot;   |-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n&quot;, eth-&gt;h_dest[0] , eth-&gt;h_dest[1] , eth-&gt;h_dest[2] , eth-&gt;h_dest[3] , eth-&gt;h_dest[4] , eth-&gt;h_dest[5] );
	fprintf(logfile , &quot;   |-Source Address      : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n&quot;, eth-&gt;h_source[0] , eth-&gt;h_source[1] , eth-&gt;h_source[2] , eth-&gt;h_source[3] , eth-&gt;h_source[4] , eth-&gt;h_source[5] );
	fprintf(logfile , &quot;   |-Protocol            : %u \n&quot;,(unsigned short)eth-&gt;h_proto);
}

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

	unsigned short iphdrlen;

	struct iphdr *iph = (struct iphdr *)(Buffer  + sizeof(struct ethhdr) );
	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  + sizeof(struct ethhdr) );
	iphdrlen = iph-&gt;ihl*4;

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

	int header_size =  sizeof(struct ethhdr) + iphdrlen + tcph-&gt;doff*4;

	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 + header_size , Size - header_size );

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

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

	unsigned short iphdrlen;

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

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

	int header_size =  sizeof(struct ethhdr) + iphdrlen + sizeof udph;

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

	//Move the pointer ahead and reduce the size of string
	PrintData(Buffer + header_size , Size - header_size);

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

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

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

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

	int header_size =  sizeof(struct ethhdr) + iphdrlen + sizeof icmph;

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

	//Move the pointer ahead and reduce the size of string
	PrintData(Buffer + header_size , (Size - header_size) );

	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>The log file will looks somewhat like this :</p>
<pre class="brush: cpp; title: Code; notranslate">

***********************TCP Packet*************************

Ethernet Header
   |-Destination Address : 00-25-5E-1A-3D-F1
   |-Source Address      : 00-1C-C0-F8-79-EE
   |-Protocol            : 8 

IP Header
   |-IP Version        : 4
   |-IP Header Length  : 5 DWORDS or 20 Bytes
   |-Type Of Service   : 0
   |-IP Total Length   : 141  Bytes(Size of Packet)
   |-Identification    : 13122
   |-TTL      : 64
   |-Protocol : 6
   |-Checksum : 45952
   |-Source IP        : 192.168.1.6
   |-Destination IP   : 74.125.71.125

TCP Header
   |-Source Port      : 33655
   |-Destination Port : 5222
   |-Sequence Number    : 78458457
   |-Acknowledge Number : 2427066746
   |-Header Length      : 5 DWORDS or 20 BYTES
   |-Urgent Flag          : 0
   |-Acknowledgement Flag : 1
   |-Push Flag            : 1
   |-Reset Flag           : 0
   |-Synchronise Flag     : 0
   |-Finish Flag          : 0
   |-Window         : 62920
   |-Checksum       : 21544
   |-Urgent Pointer : 0

                        DATA Dump
IP Header
    00 25 5E 1A 3D F1 00 1C C0 F8 79 EE 08 00 45 00         .%^.=.....y...E.
    00 8D 33 42                                             ..3B
TCP Header
    40 00 40 06 B3 80 C0 A8 01 06 4A 7D 47 7D 83 77         @.@..?....J}G}.w
    14 66 04 AD                                             .f..
Data Payload
    17 03 01 00 60 A0 9C 5D 14 A1 25 AB CE 8B 7C EB         ....`..]..%...|.
    1A A4 43 A6 60 DD E8 6B 6E 43 C1 94 6A D2 25 23         ..C.`..knC..j.%#
    03 98 59 67 1A 2C 07 D3 7E B2 B8 9F 83 38 4C 69         ..Yg.,..~....8Li
    D3 3A 8E 0D 9E F0 6B CE 9E 6B F4 E1 BD 9E 50 53         .:....k..k....PS
    6D F6 AB 11 05 D6 41 82 F0 03 0C A6 E2 48 2B 71         m.....A......H+q
    16 81 FF 5B DF 50 D4 5B AD 90 04 5E 4C 94 E7 9B         ...[.P.[...^L...
    0B 72 7E 32 88                                          .r~2.

###########################################################

***********************TCP Packet*************************

Ethernet Header
   |-Destination Address : 00-1C-C0-F8-79-EE
   |-Source Address      : 00-25-5E-1A-3D-F1
   |-Protocol            : 8 

IP Header
   |-IP Version        : 4
   |-IP Header Length  : 5 DWORDS or 20 Bytes
   |-Type Of Service   : 32
   |-IP Total Length   : 141  Bytes(Size of Packet)
   |-Identification    : 30410
   |-TTL      : 48
   |-Protocol : 6
   |-Checksum : 49112
   |-Source IP        : 74.125.71.125
   |-Destination IP   : 192.168.1.6

TCP Header
   |-Source Port      : 5222
   |-Destination Port : 33655
   |-Sequence Number    : 2427066746
   |-Acknowledge Number : 78458558
   |-Header Length      : 5 DWORDS or 20 BYTES
   |-Urgent Flag          : 0
   |-Acknowledgement Flag : 1
   |-Push Flag            : 1
   |-Reset Flag           : 0
   |-Synchronise Flag     : 0
   |-Finish Flag          : 0
   |-Window         : 63784
   |-Checksum       : 63942
   |-Urgent Pointer : 0

                        DATA Dump
IP Header
    00 1C C0 F8 79 EE 00 25 5E 1A 3D F1 08 00 45 20         ....y..%^.=...E
    00 8D 76 CA                                             ..v.
TCP Header
    00 00 30 06 BF D8 4A 7D 47 7D C0 A8 01 06 14 66         ..0...J}G}.....f
    83 77 90 AA                                             .w..
Data Payload
    17 03 01 00 60 01 B9 00 4E C7 79 0D 89 09 15 BF         ....`...N.y.....
    9C BB 53 8D 50 DB 97 4E 25 AC FA E2 55 20 94 8B         ..S.P..N%...U ..
    AF 6E 84 E2 95 8B D9 26 A3 63 7D E4 F0 CA 6F 72         .n.....&amp;.c}...or
    F6 29 95 79 98 BC 12 BF F1 C5 34 42 83 A3 F8 B6         .).y......4B....
    9E B2 7B 1C FC F7 3E BA 4E B1 FB 36 89 93 E3 58         ..{...&gt;.N..6...X
    A7 FC 5B C3 68 9E 35 CC 25 00 7D 82 3D DB 86 EA         ..[.h.5.%.}.=...
    66 89 99 B3 65                                          f...e

###########################################################
</pre>
<p>In the above log we can see the ethernet headers being printed. They show the source and destination mac address along with the packet protocol. 8 means IP protocol</p>
<p>Note :</p>
<p>1. If you want to sniff only IP and ARP packets for example then you can try this :<br />
sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_IP|ETH_P_ARP)) ;</p>
<p>The complete list of protocols is found in /usr/include/linux/if_ether.h</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
 *	These are the defined Ethernet Protocol ID's.
 */

#define ETH_P_LOOP	0x0060		/* Ethernet Loopback packet	*/
#define ETH_P_PUP	0x0200		/* Xerox PUP packet		*/
#define ETH_P_PUPAT	0x0201		/* Xerox PUP Addr Trans packet	*/
#define ETH_P_IP	0x0800		/* Internet Protocol packet	*/
#define ETH_P_X25	0x0805		/* CCITT X.25			*/
#define ETH_P_ARP	0x0806		/* Address Resolution packet	*/
#define	ETH_P_BPQ	0x08FF		/* G8BPQ AX.25 Ethernet Packet	[ NOT AN OFFICIALLY REGISTERED ID ] */
#define ETH_P_IEEEPUP	0x0a00		/* Xerox IEEE802.3 PUP packet */
#define ETH_P_IEEEPUPAT	0x0a01		/* Xerox IEEE802.3 PUP Addr Trans packet */
#define ETH_P_DEC       0x6000          /* DEC Assigned proto           */
#define ETH_P_DNA_DL    0x6001          /* DEC DNA Dump/Load            */
#define ETH_P_DNA_RC    0x6002          /* DEC DNA Remote Console       */
#define ETH_P_DNA_RT    0x6003          /* DEC DNA Routing              */
#define ETH_P_LAT       0x6004          /* DEC LAT                      */
#define ETH_P_DIAG      0x6005          /* DEC Diagnostics              */
#define ETH_P_CUST      0x6006          /* DEC Customer use             */
#define ETH_P_SCA       0x6007          /* DEC Systems Comms Arch       */
#define ETH_P_TEB	0x6558		/* Trans Ether Bridging		*/
#define ETH_P_RARP      0x8035		/* Reverse Addr Res packet	*/
#define ETH_P_ATALK	0x809B		/* Appletalk DDP		*/
#define ETH_P_AARP	0x80F3		/* Appletalk AARP		*/
#define ETH_P_8021Q	0x8100          /* 802.1Q VLAN Extended Header  */
#define ETH_P_IPX	0x8137		/* IPX over DIX			*/
#define ETH_P_IPV6	0x86DD		/* IPv6 over bluebook		*/
#define ETH_P_PAUSE	0x8808		/* IEEE Pause frames. See 802.3 31B */
#define ETH_P_SLOW	0x8809		/* Slow Protocol. See 802.3ad 43B */
#define ETH_P_WCCP	0x883E		/* Web-cache coordination protocol
					 * defined in draft-wilson-wrec-wccp-v2-00.txt */
#define ETH_P_PPP_DISC	0x8863		/* PPPoE discovery messages     */
#define ETH_P_PPP_SES	0x8864		/* PPPoE session messages	*/
#define ETH_P_MPLS_UC	0x8847		/* MPLS Unicast traffic		*/
#define ETH_P_MPLS_MC	0x8848		/* MPLS Multicast traffic	*/
#define ETH_P_ATMMPOA	0x884c		/* MultiProtocol Over ATM	*/
#define ETH_P_LINK_CTL	0x886c		/* HPNA, wlan link local tunnel */
#define ETH_P_ATMFATE	0x8884		/* Frame-based ATM Transport
					 * over Ethernet
					 */
#define ETH_P_PAE	0x888E		/* Port Access Entity (IEEE 802.1X) */
#define ETH_P_AOE	0x88A2		/* ATA over Ethernet		*/
#define ETH_P_TIPC	0x88CA		/* TIPC 			*/
#define ETH_P_1588	0x88F7		/* IEEE 1588 Timesync */
#define ETH_P_FCOE	0x8906		/* Fibre Channel over Ethernet  */
#define ETH_P_FIP	0x8914		/* FCoE Initialization Protocol */
#define ETH_P_EDSA	0xDADA		/* Ethertype DSA [ NOT AN OFFICIALLY REGISTERED ID ] */

/*
 *	Non DIX types. Won't clash for 1500 types.
 */

#define ETH_P_802_3	0x0001		/* Dummy type for 802.3 frames  */
#define ETH_P_AX25	0x0002		/* Dummy protocol id for AX.25  */
#define ETH_P_ALL	0x0003		/* Every packet (be careful!!!) */
#define ETH_P_802_2	0x0004		/* 802.2 frames 		*/
#define ETH_P_SNAP	0x0005		/* Internal only		*/
#define ETH_P_DDCMP     0x0006          /* DEC DDCMP: Internal only     */
#define ETH_P_WAN_PPP   0x0007          /* Dummy type for WAN PPP frames*/
#define ETH_P_PPP_MP    0x0008          /* Dummy type for PPP MP frames */
#define ETH_P_LOCALTALK 0x0009		/* Localtalk pseudo type 	*/
#define ETH_P_CAN	0x000C		/* Controller Area Network      */
#define ETH_P_PPPTALK	0x0010		/* Dummy type for Atalk over PPP*/
#define ETH_P_TR_802_2	0x0011		/* 802.2 frames 		*/
#define ETH_P_MOBITEX	0x0015		/* Mobitex (kaz@cafe.net)	*/
#define ETH_P_CONTROL	0x0016		/* Card specific control frames */
#define ETH_P_IRDA	0x0017		/* Linux-IrDA			*/
#define ETH_P_ECONET	0x0018		/* Acorn Econet			*/
#define ETH_P_HDLC	0x0019		/* HDLC frames			*/
#define ETH_P_ARCNET	0x001A		/* 1A for ArcNet :-)            */
#define ETH_P_DSA	0x001B		/* Distributed Switch Arch.	*/
#define ETH_P_TRAILER	0x001C		/* Trailer switch tagging	*/
#define ETH_P_PHONET	0x00F5		/* Nokia Phonet frames          */
#define ETH_P_IEEE802154 0x00F6		/* IEEE802.15.4 frame		*/
#define ETH_P_CAIF	0x00F7		/* ST-Ericsson CAIF protocol	*/
</pre>
<p>Enjoy!!</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1045&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/packet-sniffer-code-in-c-using-linux-sockets-bsd-part-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

