Tuesday, May 11, 2010

Internet Connection Sharing through WiFi with Ubuntu PC as a gateway

The Problem

I have Ubuntu installed on my notebook computer(from now onwards, I will call it host computer in this post) which has a wired ethernet connection to a broadband internet service provider. I want to have a WiFi network broadcast in my room using my host computer so that any other notebook(guest) or smart phone with WiFi capability in the vicinity can connect to the broadband internet with host notebook working as a gateway.

The solution 

I had this problem from long ago since I wanted my broadband to be shared on my Sony Ericsson P1i. and I searched whole of the internet to find a solution but none actually worked.
Today after some fiddling I finally made my P1i to hook to the broadband with Ubuntu notebook working as a gateway.

This tutorial I am presenting has been tested on Ubuntu 10.04 Lucid Lynx and works perfectly fine. I can't guarantee it to work on earlier distributions because I myself had seen funny characters in WiFi network search list in P1i on 9.10 Karmic Koala and it never worked for me.

So, lets proceed.

1. Turn on your notebook's WiFi if there's a dedicated switch to turn it on. On my Fujitsu Siemens Amilo Si 3655 notebook, WiFi can be turned on using Fn+F1 key combination.

2. Click on the Network Manager icon(which looks like ) in the notification area and click Create New Wireless Network...

3. In the dialog box that pops up, put the network name as anything(I put WLAN). Set Wireles Security as WEP 40/128-bit key. In the Key box, enter any five digit number(I entered 31323). Click Create.


4. Now right click on the Network Manager icon and click Edit Connections... In the Network Connections dialog box that pops up, go to the Wireless tab. Click WLAN(or the network name you had provided) and click Edit.


5. In the Edit WLAN dialog box that opens up, set the Mode as Ad-hoc. Make sure the Connect Automatically checkbox is checked and in the IPv4 Settings tab, and Method is set to Shared to other computers. Now click Apply.

Your network is ready!!! Congrats!!! But thats only 50 percent of the hurdle complete. You might have reached this far several times using other tutorials and how tos available on the net. Lets proceed through to get the configuration details for the client pc/notebook/smart phone.

6. Open a terminal(for eg. by pressing Alt+F2 then typing xterm and pressing enter). In the terminal type ifconfig and press enter. Scroll down tothe place where wlan0 is written. Beside that, in the second line you will see three things viz. inet addr, Bcast and Mask. Note these things somewhere safely. In my case inet addr is 10.42.43.1 and Mask is 255.255.255.0. No need to note Bcast.

7. Use the following manual configuration details for the client system:

IPv4 Addr: 10.42.43.2(for a yet another machine use 10.42.43.3 and so on...)
Subnet Mask: 255.255.255.0
DNS Address1: 208.67.222.222
DNS Address2: 208.67.220.220

After doing all this above you may notice that the client computer connects to net successfully but the host computer isn't able to access any website. Thats because the network manager blanks the DNS records set in /etc/resolv.conf

To solve this, type

sudo gedit /etc/resolv.conf

in any terminal and there append

nameserver 208.67.220.220
nameserver 208.67.222.222

and save the file. Afterwards you will be able to surf the web on gateway computer as well, normally.

You may notice that the network manager blanks out /etc/resolv.conf every now and then and you've to manually edit it and add nameservers. This is a very common problem faced by GNOME users. To get rid of this just type the following command in terminal and press enter.

chattr +i /etc/resolv.conf



Now I am going to explain how did I connect my P1i to this network to use the broadband internet.

1. Turn on Wireless LAN 

2. Touch Scan for scanning for new networks You will see the newly created network WLAN listed there with a lock icon.

3. Now go to Internet Accounts by tapping More in the WLAN page and tapping Internet Accounts.

4. There tap More>New account>WLAN

5. Fill in the details as shown in the screenshot and create the connection.



6. Now in the Internet Accounts tab highlight WLAN and tap Edit, then tap More>TCP/IP>IP Config and fill in the details as shown in the screenshot. Similarly fill in the details for the DNS address. Press Done and come back to Wireless LAN. There scan for networks. You will notice a yellow star beside th network name WLAN. Hit the Connect button after highlighting WLAN.
7. Cheers!!! You are now connected to the internet. Open web browser and test your connectivity and enjoy.

Sunday, May 9, 2010

Bug in MySQL Subqueries with IN Operator

While developing an application with MySQL at the backend I happened to write a query containing a subquery with the IN operator. I was surprised to see that the query crashed MySQL daemon on Windows! On Linux, it was taking ages and I had to abort it. After lots of tests I concluded that MySQL has a limited support for subqueries. I browsed their site for help and found out that they were working on it and it will be fixed in the 6th version.

Similarly I also found that Self-Joins have problems too, for tables with large number of entries.
Here are the queries. If you wanna experiment then download the table structure from here

The query with subquery(takes infinite time):
SELECT DISTINCT(uid) FROM ip WHERE ip IN(SELECT ip FROM ip WHERE uid=3) ORDER BY uid; 

The alternate solution using self-join(takes 5.30 seconds on my notebook):
SELECT DISTINCT(a.uid) FROM ip a, ip b WHERE a.ip=b.ip AND b.uid=3 ORDER BY a.uid;

Another solution using an inner join to an inline view(takes 2.55 seconds on my notebook):
SELECT DISTINCT(a.uid) FROM ip a, (SELECT ip FROM ip WHERE uid=3) b WHERE a.ip=b.ip ORDER BY a.uid;

or in ANSI style using the INNER JOIN keyword


SELECT DISTINCT(a.uid) FROM ip a INNER JOIN (SELECT ip FROM ip WHERE uid=3) b ON a.ip=b.ip ORDER BY a.uid;



The penultimate solution I used was through PHP by splitting the query in parts and processing through PHP. It takes 1.99 seconds to vomit the result:
<?php
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$start = $time;
$sql=mysql_query("SELECT ip FROM ip WHERE uid=3");
$condition="";
while($tmp=mysql_fetch_array($sql)){
$condition.=" ip='$tmp[0]' OR";
}
$len=strlen($condition);
$condition=substr($condition,0,len-3);
$sql=mysql_query("SELECT DISTINCT(uid) FROM ip WHERE".$condition);
          if ($sql){
  $i=0;
  while ($sqls=mysql_fetch_array($sql)){
  $iarray[$i++]=$sqls[0];
  }
  }
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$finish = $time;
$totaltime = ($finish - $start);
echo count($iarray)." rows in $totaltime seconds
";
print_r($iarray);
?>

The final solution that I implemented take 0.035 seconds!

<?php
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$start = $time;
$sql=mysql_query("SELECT ip FROM ip WHERE uid=3");
$condition="";
while($tmp=mysql_fetch_array($sql)){
$condition.="'$tmp[0]',";
}
$len=strlen($condition);
$condition=substr($condition,0,len-1);
$query="SELECT DISTINCT(uid) FROM ip WHERE ip IN(".$condition.")";
$sql=mysql_query($query);
          if ($sql){
 $i=0;
 while ($sqls=mysql_fetch_array($sql)){
 $iarray[$i++]=$sqls[0];
 }
 }
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$finish = $time;
$totaltime = ($finish - $start);
echo count($iarray)." rows in $totaltime seconds
";
print_r($iarray);
?>

Friday, May 7, 2010

IIIT-B Interview

If you are just preparing for GATE, you should solve more and more questions. And for that I would recommend GKP Publisher's Question Bank. Although there are some mistakes in the book for solutions to some problems, but I recommend this book solely for the huge collection of problems it has.

On the destined date I reached Bangalore for my IIIT-B interview. Bangalore is quite a happening city. Contrary to the fact pointed out by my acquaintances that you will have language problems in Bangalore, everyone seemed to understand Hindi and English. On 5th morning at 7AM I boarded a bus from Majestic for Electronics City. It took around 45 minutes for the AC Volvo called Vayu Vajra by BMTC, to churn out 15KMs, traffic being a bottleneck. I was greeted by the Electronics City flagship Infosys campus. It is very huge and a live example of engineering and architectural excellence. After asking a few passers-by about the where-abouts of IIIT-B we finally found the campus which has an HP go-down(housed in Infosys campus) in its front, Siemens to the left, Infosys to the front right. As I entered the campus I noticed a gathering of several GATE qualified padhaku students. I took an stroll around the campus with inquisitive eyes, and then entered into the academic block from the rear!!! As I entered inside, I was awestruck at the beauty of the interior. After I detected my goof, I went to the main entrance and got my attendance marked. Then I was directed to head towards Main Class Room 106. There, lots of students and their guardians were seated, and catered by the student volunteers. The main class room had four large projected screens and the student volunteers were running presentations about the college on them and helping the candidates with the interview process. They were all very co-operative. Some YouTube videos were also being played. The internet connectivity through WiFi was extremely fast there and I saw a 4 minute video getting buffered in less than 30 seconds.
At around 12 I went for my documents verification and was then carried to the interview place. There were around 20 cabins in which 20 people were interviewing the candidates. After a couple of minutes I was directed towards a cabin. I asked for the permission to enter and went into the chamber. The man inside offered me a seat, I thanked and seated myself onto the chair.
My interview session lasted for around 15-20 minutes. The first thing he asked me was: Tell me about yourself for three minutes. I started off with the by hearted answer that consisted of Name, Location, Schooling, Current activity, Hobbies and Interests in that order. Instead of 3 minutes, I ran out of data in 1 minute only!!!
Then he asked me about my blog, about which I had stated in the hobbies category. I spoke. He cross-questioned, how many followers do you have? I said two, as of now, but I receive 100+ unique visitors per day according to log stats. He asked me why don't you concentrate on converting visitors to followers? I said, I didn't have this idea earlier, my main motto was to acquaint people with my experiences with computers, but now as you have told me I'll concentrate on this thing too.
Then he asked me. Ok, start with the technical topic you have prepared and continue for five minutes. I started off with my Socket Communication topic and explained things bringing everything down to basic level. During the course of describing the UDP server I forgot something and stopped, then asked him for a few seconds to recall and reorganize all the data inside my brain. He gave me time and after 3 seconds I resumed.
After I finished, he said you can communicate well, but not because you have a very good command over spoken english but because you have a deep understanding of the topic you are explaining. I said yes sir, my mothertongue is not english and I have spoken english very little so I don't have very good command over spoken english. He told, who says you can't speak? You spoke perfectly well. Communication means when you speak socket, I should hear it as socket not ice cream! I agreed!
Then he started looking at my academics. He said you're having nice academics. Your GATE score of 614 and marks 42.33 is very high and you're probably in the 98th percentile. I said yes, 98.59 to be precise. He said, it is a very good score. I replied, not very good but it is just fine, I could have scored 60+ if only I hadn't made those silly mistakes which I realized while matching the solutions on v-day evening. Then he said, which subjects you were most excited about in your B.Tech. I replied DBMS and Networking. He said, ok you've been given a table, can you say whether it is in third normal form and if it is not, then can you convert it in 3NF? Backed with my expertise in Functional Dependencies & Normalization I said, yeah with hundred percent surety, and proceeded ahead.
After this he asked me, how do you spend your time. I said, I am not into arts so no music, no singing. But I play chess, do some photography and most of the extra time I spend managing my site. Then he asked me about the site. I explained about IndiFun using the word Mobile Social Networking. He stressed on the phrase and said me to explain it. I explained about GPRS and tiny browsers and mobile markup languages. He said, how does this site connect people. I narrated all the features of IndiFun like an advertiser!!!!
Then he said, according to your academics and your extra-curricular activities you are a very deserving candidate. I would love to have you here. But the interview is a very tiny part of the whole selection process. My best wishes for you.
And said, if you have any questions then ask me. I asked, please tell me about yourself. He said, I run a company called Radix Learning which works with IIIT-B and also I teach here data structures in PGDSD course, not in M.Tech course. I said, I would like to keep in touch with you after I get selected. He said no! I don't interact with M.Tech students!
After that he said go happy, you seem to be a very promising candidate. I thanked him, shook hands and left the cabin.
Some photos that I took, follow:










Sunday, April 18, 2010

My own chat application in C!!!!

After an standing-out(not outstanding :P) performance in GATE 2010 and missing the prestigious 99th percentile with just one question, I have to console myself for my shattered dream of being an IITian. I am looking for Tier-2 colleges now(I call IITs as tier-1 and NITs and IIITs as tier-2). I got an interview call from IIIT-B to be held on May 5th. In their interview a candidate has to present a technical talk of 5-10 minutes on any technical topic of his/her choice. He/She is then fired questions from the same topic by the selection committee. I have decided to speak on the topic "SOCKET COMMUNICATION". While the preparation I thought I should have an inside view of how it works by developing an application using it. After lots of research on the internet and many trial and errors I finally coded this crude chat application in C. You may also use it in your assignment if you're a student in search for stuff to do your assignments.

Note:
When one user is typing the message, the second one should not write anything :P i.e. it works similar to a walkie talkie.


Usage:
1. Compile the code into an object file and link the object file with wsock32.lib to generate the executable. I designed it and compiled it with Digital Mars Compiler & Linker You may use any compiler but you may need to modify the code a bit, based on your compiler.

To compile and link on dmc(that stands for Digital Mars Compiler) use these commands:
dmc -c chat.c
dmc chat.o wsock32.lib

2. You can test this app on two PCs/Laptops on LAN/WLAN. Launch it through command line on one computer. On the second launch it with the ip address of first computer as the command line argument.
For example(assuming it is placed in D:\'s root with the name chat.exe)
On first computer:
1. Window Key+R
2. Type cmd and press enter
3. Type d:\chat and press enter

On second computer:
1. Window Key+R
2. Type cmd and press enter
3. Type d:\chat <ip_of_first_comp.> like d:\chat 192.168.0.1



Download the executable here

Here is the source code:


#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>

#define MAXPENDING 1 /* Maximum outstanding connection requests */

void DieWithError(char *errorMessage); /* Error handling function */

void main(int argc, char *argv[])
{
short runtype; /* 0 for client, 1 for server*/
int serv_sock; /* Socket descriptor for server */
int clnt_sock; /* Socket descriptor for client */
struct sockaddr_in serv_addr; /* Server address */
struct sockaddr_in clnt_addr; /* Client address */
unsigned short port=9797; /* Port for communication */
unsigned int clnt_len; /* Length of client address data structure */
char msg[1024]; /* For chat message */
int msg_len;
int bytes; /* Byte count for received data */
WSADATA wsaData; /* Structure for WinSock setup communication */


switch(argc){
case 1:
runtype=0;
break;
case 2:
runtype=1;
break;
default:
printf("Invalid use of application. Usage: %s [<ip_addr>]",argv[0]);
exit(1);
break;
}

if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) /* Load Winsock 2.0 DLL */
{
fprintf(stderr, "WSAStartup() failed");
exit(1);
}


if (runtype==0){
/* Create socket for incoming connections */
if ((serv_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");

/* Construct local address structure */
memset(&serv_addr, 0, sizeof(serv_addr)); /* Zero out structure */
serv_addr.sin_family = AF_INET; /* Internet address family */
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
serv_addr.sin_port = htons(port); /* Port */

/* Bind to the local address */
if (bind(serv_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
DieWithError("bind() failed");

/* Mark the socket so it will listen for incoming connections */
if (listen(serv_sock, MAXPENDING) < 0)
DieWithError("listen() failed");

/* Set the size of the in-out parameter */
clnt_len = sizeof(clnt_addr);
/* Wait for a client to connect */
printf("Waiting for a user to connect...\n");
if ((clnt_sock = accept(serv_sock, (struct sockaddr *) &clnt_addr, (int *)&clnt_len)) < 0)
DieWithError("accept() failed");
printf("Connected to %s. Type message and press enter to send. Ctrl+C to terminate.\n\n", inet_ntoa(clnt_addr.sin_addr));
while(1){
/* Receive message from client */
if ((bytes = recv(clnt_sock, msg, 1024, 0)) < 0)
DieWithError("recv() failed");
/*Put a null terminator at the last byte*/
msg[bytes]='\0';
printf("%s says: %s\n",inet_ntoa(clnt_addr.sin_addr),msg);
printf("You say: ");
gets(msg);
msg_len=strlen(msg);
if (send(clnt_sock, msg, msg_len, 0) != msg_len)
DieWithError("send() failed");
}
}
else if(runtype==1){
char *serv_ip;
serv_ip=argv[1];
/* Create a reliable, stream socket using TCP */
if ((clnt_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
/* Construct the server address structure */
memset(&serv_addr, 0, sizeof(serv_addr)); /* Zero out structure */
serv_addr.sin_family = AF_INET; /* Internet address family */
serv_addr.sin_addr.s_addr = inet_addr(serv_ip); /* Server IP address */
serv_addr.sin_port = htons(port); /* Server port */
/* Establish the connection to the chat server */
if (connect(clnt_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
DieWithError("connect() failed");
printf("Connected to %s. Type your message and press enter to send. Ctrl+C to terminate.\n\n",argv[1]);

while(1){
printf("You say: ");
gets(msg);
msg_len = strlen(msg); /* Determine input length */
/* Send the string, including the null terminator, to the server */
if (send(clnt_sock, msg, msg_len, 0) != msg_len)
DieWithError("send() sent a different number of bytes than expected");
if ((bytes = recv(clnt_sock, msg, 1024, 0)) <= 0)
DieWithError("recv() failed or connection closed prematurely");
msg[bytes]='\0';
printf("%s says: %s\n", argv[1], msg); /* Print the message */
}
}
}
void DieWithError(char *errorMessage)
{
fprintf(stderr,"%s: %d\n", errorMessage, WSAGetLastError());
exit(1);
}