<?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</title>
	<atom:link href="http://www.binarytides.com/blog/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>Compile wxwebconnect on Ubuntu 11.04 64 bit</title>
		<link>http://www.binarytides.com/blog/compile-wxwebconnect-on-ubuntu-11-04-64-bit/</link>
		<comments>http://www.binarytides.com/blog/compile-wxwebconnect-on-ubuntu-11-04-64-bit/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 09:31:28 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[ubuntu]]></category>
		<category><![CDATA[wxwidgets]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1346</guid>
		<description><![CDATA[wxwebconnect is a control for wxwidgets that allows to embed a gecko browser in a wxwidgets application. So lets try to install it on Ubuntu 11.04 wxWidgets can be installed from synaptic. Look for packages called libwxgtk2.8-* 1. Download wxwebconnect source from http://www.kirix.com/labs/wxwebconnect/downloads.html Extract them in home directory. Inside the webconnect directory you would see directories like webconnect , xr and testapp. 2. Over here create a directory called wxWidgets. Download wxwidgets 2.8.12 from here [...]]]></description>
			<content:encoded><![CDATA[<p>wxwebconnect is a control for wxwidgets that allows to embed a gecko browser in a wxwidgets application.</p>
<p>So lets try to install it on Ubuntu 11.04</p>
<p>wxWidgets can be installed from synaptic. Look for packages called libwxgtk2.8-*</p>
<p>1. Download wxwebconnect source from http://www.kirix.com/labs/wxwebconnect/downloads.html<br />
Extract them in home directory. Inside the webconnect directory you would see directories like webconnect , xr and testapp.</p>
<p>2. Over here create a directory called wxWidgets. Download wxwidgets 2.8.12 from here http://www.wxwidgets.org/downloads/<br />
wxGTK for Ubuntu.</p>
<p>3. Extract wxwidgets inside  /home/user/webconnect-1.1/wxWidgets</p>
<p>4. You would also need libgtk2.0-dev first, so installed it from synaptic. Now do a ./configure and make for wxwidgets<br />
Once this process is over wxwidgets should be build.</p>
<p>5. Now do a make inside /home/user/webconnect-1.1/webconnect</p>
<p>6. Now do a make inside /home/user/webconnect-1.1/testapp.</p>
<p>7. Now everything is compiled. But one this still remains is xulrunner. You need xulrunner 1.9.x . The one available on Mozilla website will not work. So lets do a trick. Install the xulrunner-1.9.2 package from synaptic.</p>
<p>It will install all xulrunner files in /usr/lib/xulrunner-1.9.2.17/ or a similar location. Go there and copy everything. First empty the /home/user/webconnect-1.1/xr directory and then paste everything here.</p>
<p>8. Now go inside testapp and execute the testapp binary which we created a while back. It should run and open webpages fine.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1346&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/compile-wxwebconnect-on-ubuntu-11-04-64-bit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Disqus Comments Importer Script in PHP</title>
		<link>http://www.binarytides.com/blog/disqus-comments-importer-script-in-php/</link>
		<comments>http://www.binarytides.com/blog/disqus-comments-importer-script-in-php/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 14:43:40 +0000</pubDate>
		<dc:creator>f00</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[disqus. commenting]]></category>
		<category><![CDATA[importer]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1326</guid>
		<description><![CDATA[Disqus is a great commenting platform that does it&#8217;s job really well. Many people use it these days because writing your own commenting system is a tedious and hard work whereas a solution like Disqus or Livefyre makes the entire commenting process a breeze with features like social logins, many levels of nesting, easy replying, quick and realtime commenting, easy integration, intuitive admin panel to manage your comments, email notifications, managing comments via emails directly, [...]]]></description>
			<content:encoded><![CDATA[<p><a target="_blank" href="http://disqus.com/" title="Disqus" >Disqus</a> is a great commenting platform that does it&#8217;s job really well. Many people use it these days because writing your own commenting system is a tedious and hard work whereas a solution like Disqus or Livefyre makes the entire commenting process a breeze with features like social logins, many levels of nesting, easy replying, quick and realtime commenting, easy integration, intuitive admin panel to manage your comments, email notifications, managing comments via emails directly, etc.</p>
<p>From their website -</p>
<blockquote><p>DISQUS is a comments platform that helps you build an active community from your website&#8217;s audience. It has awesome features, powerful tools, and it&#8217;s easy to install.</p></blockquote>
<p>Recently I moved from Disqus to my own custom commenting system for several reasons like more control over comment notifications to authors, showing comments count anywhere easily, etc. So I had to figure out a way to move about a hundred comments from Disqus&#8217;s system to my own Database. Googling did not help me find any good script for such a requirement neither did Github Search yield anything. So, I decided to give it a shot, took some time as I had to do it with <a target="_blank" href="http://php.net/dom" title="PHP DOM" >http://php.net/dom</a> and had no previous experience but overall it wasn&#8217;t more than a day&#8217;s task and most of it was a breeze. I would like to share the code here just incase it helps others!</p>
<p>First of all check out this link - <a target="_blank" href="http://docs.disqus.com/developers/export/" >http://docs.disqus.com/developers/export/</a>. It shows the XML Export Format and has other valuable information too.</p>
<h2>Exporting the Comments</h2>
<p>Exporting the comments is really very easy. Login to your Disqus account and then click your Site from the Site list. You will then see the Tools tab in the menu, click that and finally click the Export tab.</p>
<p><a href="http://www.binarytides.com/blog/disqus-comments-importer-script-in-php/screenshot-7-2/"  rel="attachment wp-att-1341"><img class="alignnone size-full wp-image-1341" title="Screenshot-7" src="http://www.binarytides.com/blog/wp-content/uploads/2012/01/Screenshot-7.png" alt="Disqus Admin Panel" width="600" height="334" /></a></p>
<h2>Code in Action</h2>
<pre class="brush: php; title: Code; notranslate">

function import() {
 date_default_timezone_set('GMT');

 $res = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

 $file = '/path/to/disqus/export.xml';
 $doc = new DOMDocument();
 $doc-&gt;load($file);
 // echo $doc-&gt;saveXML();

 $thread_list = array();
 $threads = $doc-&gt;getElementsByTagName('thread');
 foreach( $threads as $thread ) {
  $comment = array();
  $comment['thread_id'] = $thread-&gt;getAttribute('dsq:id');
  $comment['url'] = $thread-&gt;getElementsByTagName('link')-&gt;item(0)-&gt;nodeValue;
  $comment['url_parts'] = explode('/', $comment['url']);

  if ( $comment['url_parts'][3] != 'item' ) continue;

  $comment['item_id'] = (int) $comment['url_parts'][4];
  $thread_list[$comment['thread_id']] = $comment;
 }

 // var_dump($thread_list);

 $post_list = array();
 $posts = $doc-&gt;getElementsByTagName('post');
 $i = 1;
 foreach( $posts as $post ) {
  $comment = array();
  $comment['id'] = $i;
  $comment['comment_id'] = $post-&gt;getAttribute('dsq:id');

  if ( in_array($comment['comment_id'], array('386444814', '389840029', '410354950', '412405419')) ) continue;

  $comment['comment'] = str_replace(&quot;
&quot;, &quot;\r\n&quot;, $post-&gt;getElementsByTagName('message')-&gt;item(0)-&gt;nodeValue);
  $comment['ip_address'] = $post-&gt;getElementsByTagName('ipAddress')-&gt;item(0)-&gt;nodeValue;
  $comment['created_at'] = strtotime( str_replace(array('T', 'Z'), array(' ', ''), $post-&gt;getElementsByTagName('createdAt')-&gt;item(0)-&gt;nodeValue) );

  $comment['email'] = $post-&gt;getElementsByTagName('author')-&gt;item(0)-&gt;getElementsByTagName('email')-&gt;item(0)-&gt;nodeValue;
  $comment['name'] = $post-&gt;getElementsByTagName('author')-&gt;item(0)-&gt;getElementsByTagName('name')-&gt;item(0)-&gt;nodeValue;

  $comment['thread_id'] = $post-&gt;getElementsByTagName('thread')-&gt;item(0)-&gt;getAttribute('dsq:id');
  if ( $post-&gt;getElementsByTagName('parent')-&gt;item(0) ) {
   $comment['d_parent_id'] = $post-&gt;getElementsByTagName('parent')-&gt;item(0)-&gt;getAttribute('dsq:id');
   $comment['parent_id'] = $post_list[$comment['d_parent_id']]['id'];
  }

  $comment['item_id'] = $thread_list[$comment['thread_id']]['item_id'];
  if ( !$comment['item_id'] ) continue;

  $post_list[$comment['comment_id']] = $comment;
  ++$i;
 }

 // var_dump($post_list);

 foreach($post_list as $post) {
  $name = mysqli_real_escape_string($res, $post['name']);
  $email = mysqli_real_escape_string($res, $post['email']);
  $url = mysqli_real_escape_string($res, $post['url']);
  $comment = mysqli_real_escape_string($res, $post['comment']);
  $parent_id = (int) $post['parent_id'];
  $depth = (int) $post['depth'];
  $ip_address = mysqli_real_escape_string($res, $post['ip_address']);

  $sql = &quot;INSERT INTO comment SET item_id = $post[item_id], name = '$name', email = '$email', url = '$url', comment = '$comment', ip_address = INET_ATON('$ip_address'), parent_id = $parent_id, depth = $depth, created_at = FROM_UNIXTIME($post[created_at])&quot;;
  // echo $sql;
  mysqli_query($res, $sql);
 }
}
</pre>
<p>The disqus export file is kind of divided into 2 sections. First there is the XML for threads and then there is the XML for various comments (called post) that is related to different threads. So, in this code we first form a big array of the threads and then a big array of the comments. Then it&#8217;s pretty easy to insert the comments data into the Database.</p>
<p>There are some confusing spots in the code, let&#8217;s go through them once.</p>
<p><code>if ( $comment['url_parts'][3] != 'item' ) continue;</code> &#8211; You will notice this piece of code. Ok, so in my website there are 2 different types of resources. One is items and another is posts. So i have URLs like http://example.com/item/[item_id] and http://example.com/post/[post_id]. With this piece of code I made sure that i am only fetching the comments that belongs to my items and not posts. You can run the same code again for posts and have a comment_type column in your comment table.</p>
<p><code>$comment['url_parts'] = explode('/', $comment['url']);</code> &#8211; Disqus links your comments to your Permalinks (Item/Post URL). So exploding the URL and getting the 4th index of the array was the best way for me to obtain the Item IDs.</p>
<p><code><br />
if ( $post-&gt;getElementsByTagName('parent')-&gt;item(0) ) {<br />
$comment['d_parent_id'] = $post-&gt;getElementsByTagName('parent')-&gt;item(0)-&gt;getAttribute('dsq:id');<br />
$comment['parent_id'] = $post_list[$comment['d_parent_id']]['id'];<br />
}<br />
</code><br />
Every non-top level Disqus Comment in the XML Export has its parent_id. So if a parent_id exists, we store them in d_parent_id key and in parent_id we store &#8220;our system&#8217;s&#8221; item&#8217;s parent id. Hope that makes sense.</p>
<p><code>$comment['id'] = $i;</code> &#8211; This data acted as the Auto Increment (Primary Key) value in the Database table. This is the same value stored in parent_id for comments that have a parent above.</p>
<p>I really hope the entire code serves to be useful for a lot of people looking for a script to import disqus comments in their own system. Lets discuss more in the comments :)</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1326&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/disqus-comments-importer-script-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>str_replace for C</title>
		<link>http://www.binarytides.com/blog/str_replace-for-c/</link>
		<comments>http://www.binarytides.com/blog/str_replace-for-c/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 12:33:25 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[c]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1262</guid>
		<description><![CDATA[Php has a useful function called str_replace which can search and replace a certain string in another big string. However there is no such function in C. So I wrote up one for myself. Here is the code. Usage Output]]></description>
			<content:encoded><![CDATA[<p>Php has a useful function called str_replace which can search and replace a certain string in another big string. However there is no such function in C. So I wrote up one for myself. Here is the code.</p>
<pre class="brush: cpp; title: Code; notranslate">
/*
 * 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><strong>Usage</strong></p>
<pre class="brush: cpp; title: Code; notranslate">
/*
 * @brief
 * PHP's str_replace ported to C
 * @author Silver Moon (m00n.silv3r@gmail.com)
 * */

#include&lt;stdio.h&gt;
#include&lt;string.h&gt;
#include&lt;stdlib.h&gt;

char *str_replace(char *search , char *replace , char *subject);

int main()
{
	char *a = &quot;allblldddlll&quot;;
	char *c = str_replace(&quot;ll&quot; , &quot;xll&quot; , a);
	puts(c);
	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><strong>Output</strong></p>
<pre class="brush: bash; title: Code; notranslate">
axllbxlldddxlll
</pre>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1262&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/str_replace-for-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Easy to use C/C++ IDE for Ubuntu Linux</title>
		<link>http://www.binarytides.com/blog/easy-to-user-c-ide-for-ubuntu-linux/</link>
		<comments>http://www.binarytides.com/blog/easy-to-user-c-ide-for-ubuntu-linux/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 14:09:12 +0000</pubDate>
		<dc:creator>Binary Tides</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://www.binarytides.com/blog/?p=1252</guid>
		<description><![CDATA[Here are some IDEs that work very well on Ubuntu ( and other Linuxes ) and can be used as an alternative to the terminal gcc or g++ thing. Geany Url : http://www.geany.org/ Install with sudo apt-get install geany Open any C/C++/PHP/Html/Python/Perl file and start coding. Compile with F8 , Build with F9 and execute with F5. Very simple indeed. Has many other features. No configuration needed! CodeBlocks This one is there in the Synaptic. [...]]]></description>
			<content:encoded><![CDATA[<p>Here are some IDEs that work very well on Ubuntu ( and other Linuxes ) and can be used as an alternative to the terminal gcc or g++ thing.</p>
<h3>Geany</h3>
<p>Url : <a target="_blank" href="http://www.geany.org/" >http://www.geany.org/</a></p>
<p>Install with <code>sudo apt-get install geany</code></p>
<p><a href="http://www.binarytides.com/blog/easy-to-user-c-ide-for-ubuntu-linux/geany/"  rel="attachment wp-att-1253"><img src="http://www.binarytides.com/blog/wp-content/uploads/2011/12/geany-800x432.png" alt="" title="geany" width="800" height="432" class="aligncenter size-medium wp-image-1253" /></a></p>
<p>Open any C/C++/PHP/Html/Python/Perl file and start coding. Compile with F8 , Build with F9 and execute with F5.<br />
Very simple indeed. Has many other features.<br />
No configuration needed!</p>
<h3>CodeBlocks</h3>
<p>This one is there in the Synaptic. Simply do a <code>sudo apt-get install codeblocks</code> and you are done.</p>
<p><a href="http://www.binarytides.com/blog/easy-to-user-c-ide-for-ubuntu-linux/codeblocks/"  rel="attachment wp-att-1254"><img src="http://www.binarytides.com/blog/wp-content/uploads/2011/12/codeblocks-800x432.png" alt="" title="codeblocks" width="800" height="432" class="aligncenter size-medium wp-image-1254" /></a></p>
<p>Start coding a C/C++ program and then press F9 to build and Run. Indeed much faster than the terminal.<br />
No configuration needed!</p>
<p>There are other IDEs like Kdevelop , Anjuta , Codelite , Netbeans etc but all of them need too much of configuration before even a single piece of simple code can be run. That is where geany and codeblocks help. Very efficient for testing single file programs.</p>
<img src="http://www.binarytides.com/blog/?ak_action=api_record_view&id=1252&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.binarytides.com/blog/easy-to-user-c-ide-for-ubuntu-linux/feed/</wfw:commentRss>
		<slash:comments>1</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>
	</channel>
</rss>

<!-- Dynamic page generated in 1.028 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-02-06 20:40:10 -->

