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

Tuesday, April 6, 2010

For the undergraduates

Not only B.E./B.Tech, but there are several courses out there that teach C/C++ in 1st or 2nd semester. Students who don't have slightest idea of this language at this tender age run helter-skelter to complete their assignments. For them, I'm posting here all the programs that I developed/wrote/coded for assignments when I was in second semester, thats long back in first half of 2007. Copy these, learn these, understand these, throw these, I don't care. I'm upping them here with a hope that they will be of some use to someone in great need indeed.

Disclaimer: These are programs, not software(if you consider IEEE definition of software) so these don't have any documentation, nor do I guarantee their successful run in all test cases. Its up to you to edit, modify, improve the programs. At the time of posting I didn't check the programs, so I won't be liable for any bugs. ANother thing is that these programs should be bug free. If you are getting any error from your compiler then it may be some trivial issues like conio.h or anything like that. In such a case do some research and elliminate the bug yourself, this will help you in your academics. But if you aren't able to do, then post a comment here and tell me which program is giving what error in which compiler and I'll post the solution.

Here I start, from easy to tougher:

1. Program to print the table of a user entered number.

#include <iostream.h>
int a, i;
int main()
{
cout<<"Enter the number whose table u want to print:\n ";
cin>>a;
for(i=1;i<=10;i++)
{
cout<<a<<" * "<<i<<"="<<a*i<<"\n";
}
return (0);
}


2. Program to find factorial of a number using recursion

#include <iostream.h>
long double fact(long int num){
if (num==1){
return (1);
}
else{
return (double)(num*fact(num-1));
}
}
int main(){
long int a;
cout<<"Enter number:\n";
cin>>a;
cout<<fact(a)<<endl;
return (0);
}



3. Program to find sum of digits of a number

#include <iostream.h>
#include <conio.h>
void main(){
int a, s=0, i, r;
cout<<"Enter the number: ";
cin>>a;
for(i=0; a>=9; i++){
r=a%10;
a=(a/10);
s=s+r;
}
cout<<"The sum of digits is: "<<s+a;
getch();
}



4. Program to simplify a rational number to fractions(e.g. 6/8 to 3/4)

#include<iostream.h>
void fract(int a, int b){
int min=a;
if(b<min){
min=b;
}
for(int n=1; n<=min; n++){
if((a % n == 0) && (b % n == 0)){
a=a/n;
b=b/n;
min=min/n;
n=1;

}
}
cout<<"The required fraction is "<<a<<"/"<<b;
}

void main()
{
int x, y;
cout<<"Enter the numerator:";
cin>>x;
cout<<"Enter the denominator:";
cin>>y;
fract(x, y);
}



5. Pogram to find whether a string is a palindrome or not

#include <stdio.h>
//#include <conio.h>
#include <process.h>
void main(){
char input[20];
int length=0;
printf("Enter the word for palindrome test:\n");
gets(input);
//Find the length of entered string
while(input[length]!='\0'){
length++;
}
//Now check for palindrome status
for (int i=0; i<=length--; i++){
if (input[i]!=input[length]){
printf("Entered word isn't a palindrome.");
exit(0);
}
}
printf("Entered word is a palindrome.");
// getch();
}


6. Program to print all prime numbers upto the number input by the user

#include <iostream.h>
#include <math.h>
int main(){
int i=0, n, j=0, flag=0, mid;
cout<<"Enter the number upto where you want prime numbers to be displayed:\n";
cin>>n;
cout<<"Following are the required prime numbers:\n2\n3\n";
for(i=2;i<=n;i++){
mid = floor(sqrt(i));
for(j=2;j<=mid;j++){
if(i%j==0){
flag=0;
break;
}
else{
flag=1;
}
}
if(flag==1){
cout<<i<<"\n";
}
}
return (0);
}

7. Your own strlen function. Program to find the length of a user input string

#include <iostream.h>
int i;
int strlen(char *input){
for(i=0; input[i]!='\0'; i++){
}
return i;
}
int main(){
char *data;
cin>>data;
cout<<strlen(data);
return (0);
}


8. Your own strrev function. Program to reverse a user input string

#include <iostream.h>
#include <stdio.h>
int main(){
char *name;
cout<<"Enter the string:";
gets(name);
int count=0;
for(int i=0; name[i]!='\0'; i++){
count++;
}
for (int i=count; i>=0; i--){
cout<<name[i];
}
return (0);
}

9. Program to reverse a number

#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
int y=1,revs=0;
cout<<"No daalo";
cin>>a;
while(y>0)
{
b=a%10;
a=a/10;
revs=revs*10+b;
y=a;
}
cout<<revs;
getch();
}


10. Demonstrate a practical use of switch case

#include<iostream.h>
#include<conio.h>
int main()
{
float r,a;
char n;
cout<<"To find area of circle press C and for sphere press S:";
cin>>n;
switch(n)
{
case 'c':
{
cout<<"Enter the radius of the circle: ";
cin>>r;
a=3.1414*r*r;
cout<<"Area of the circle is " <<a;
break;
}
case 's':
{
cout<<"Enter the radius of the sphere: ";
cin>>r;
a=4*3.1414*r*r;
cout<<"Area of the sphere is " <<a;
break;
}
default:
cout<<"invalid entry!!!!!!!";
}
getch();
return(0);
}



11. Program to compute the union of 2 or more sets

#include <iostream.h>
int b;
int howmany(){
cout<<"How many elements you want to enter in this set";
cin>>b;
return b;
}
void main(){
int a, c[100], i=0, j=0, k=0;
cout<<"How many sets do you want to enter?";
cin>>a;
if (a<2){
cout<<"Blah blah! Enter at least two sets moron, for computation of union!";
}

for(int m=k;k<a;m++){
j=j+howmany();

cout<<"Enter the elements of this set one by one\n";
for(int n=i;i<j;n++)
{
cin>>c[i];
i++;
}
k++;
}

int temp=0;
for(a=0;a<i;a++){
for(b=a+1;b<i;b++){
if(c[a]==c[b]){
c[b]=0;
}

}
}
/////////////////////
cout<<"The union of all the sets above is:\n";
for (a=0;a<i;a++){
if (c[a]!=0){
cout<<c[a]<<"\n";
}
}
}



12. Program for matrix addition and multiplication using operator overloading and classes and ADT

#include <iostream.h>
int i, j, k, num;
class matrix{
int element[3][3];
public:
void display(){
for (int i=0;i<=2;i++){
for(int j=0; j<=2; j++){
cout<<element[i][j];
cout<<"\t";
}
cout<<"\n";
}
}
void getdata(){
cout<<"Enter the elements of matrix row wise:\n";
for (int i=0;i<=2;i++){
for(int j=0; j<=2; j++){
cin>>element[i][j];
}
cout<<"\n";
}
}

matrix operator +(matrix target){
matrix temp;
for(int i=0;i<=2;i++){
for(int j=0;j<=2;j++){
temp.element[i][j] = element[i][j]+target.element[i][j];
}
}
return temp;
}
matrix operator *(matrix target){
matrix temp;
int num=0;
for (i=0;i<=2;i++){
for(j=0;j<=2;j++){
for(k=0;k<=2;k++){
num = ((element[i][k])*(target.element[k][j]) + num);
}
temp.element[i][j] = num;
num=0;
}
}
return temp;
}
};
void main(){
matrix a, b,c ,d;
a.getdata();
b.getdata();
c.getdata();
d=a*b+c;
d.display();

}



13. Program to find the age difference between two dates using operator overloading and classes and ADT (Note that, calculating age difference is not as simple as normal subtraction other 3 part data like KM,M and CM trio)

#include <iostream.h>
#include <process.h>
class date{
int day;
int month;
int year;
bool leap;
public:
void getdata(void){
cout<<"Enter year(eg. 1988): \n";
cin>>year;
if((year%100)==0){
if((year%400)==0){
leap=true;
}
}
else if((year%4)==0){
leap=true;
}
else leap=false;
inmonth:
cout<<"Enter month(eg. 11): \n";
cin>>month;
if((month>12) || (month<1)){
cout<<"Invalid month entered. Please re-enter:\n";
goto inmonth;
}
inday:
cout<<"Enter day(eg. 25):\n";
cin>>day;
if((day>31) || (day<1)){
cout<<"Invalid day entered. Please re-enter:\n";
goto inday;
}
else if(((4==month)||(6==month)||(9==month)||(11==month))&&(day>30)){
cout<<"This month can't have more than 30 days. Please re-enter:\n";
goto inday;
}
else if((2==month)&&(leap==true)&&(day>29)){
cout<<"February can't have more than 29 days in a leap year. Please re-enter:\n";
goto inday;
}
else if((2==month)&&(leap==false)&&(day>28)){
cout<<"February can't have more than 28 days in a non-leap year. Please re-enter:\n";
goto inday;
}
}
void disp(){
cout<<year<<" years "<<month<<" months "<<day<<" days\n";
}
date operator-(date target){
int last_day_diff;
date result;
if(target.year>year){
cout<<"Please enter a higher date to subtract.";
exit(0);
}
if(target.day<=day){
result.day=day-target.day;
}
else if(target.day>day){
switch (month){
case 4:
case 6:
case 9:
case 11:
last_day_diff=30-target.day;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
last_day_diff=31-target.day;
break;
}
if ((true==leap)&&(2==month)){
last_day_diff=29-target.day;
}
else if((false==leap)&&(2==month)){
last_day_diff=28-target.day;
}
result.day=last_day_diff+day;
month--;
}
if(target.month<=month){
result.month=month-target.month;
}
else if(target.month>=month){
result.month=12-target.month+month;
year--;
}
result.year=year-target.year;
return result;
}
};


int main() {
date a, b, result;
cout<<"Enter higher date:\n";
a.getdata();
cout<<"Enter lower date:\n";
b.getdata();
result=a-b;
result.disp();
return 0;
}



14. Program to add and multiply two complex numbers using class, operator overloading, ADT

#include <iostream.h>

int abs(int input){
if (input>=0){
return input;
}
else{
return (-1*input);
}
}

class complex{
public:
int number[2]; //array to store real and imaginary part
complex(){ //constructor to intialize to zero
number[0]=0;
number[1]=0;
}

void display(){
if (number[1]>0){
cout<<number[0]<<"+"<<number[1]<<"i";
}
if (number[1]<0){
cout<<number[0]<<"-"<<abs(number[1])<<"i";
}
cout<<"\nReal part is: "<<number[0]<<" and imaginary part is: "<<number[1];

}

void getdata(){
cout<<"Enter real part:";
cin>>number[0];
cout<<"Enter imaginary part:";
cin>>number[1];

}

complex operator +(complex target){
complex temp;
temp.number[0] = number[0]+target.number[0];
temp.number[1] = number[1]+target.number[1];
return temp;
}

complex operator *(complex target){
complex temp;
temp.number[0] = (number[0]*target.number[0])-(number[1]*target.number[1]);
temp.number[1] = (number[0]*target.number[1])+(number[1]*target.number[0]);
return temp;
}

};
void main(){
complex a, b, c ,d;
a.getdata();
b.getdata();
c.getdata();
d=a*b+c;
d.display();

}



15. Program to print all ascii printable characters in a file instead of screen

#include <iostream.h>
#include <fstream.h>
int main(){
char i;
char path[255];
cout<<"Enter path:\n";
cin>>path;
ofstream file(path);
for(i=48; i<=122; i++){
file<<i<<"\n";
}
cout<<"Data written. Exiting";

return (0);
}

Saturday, April 3, 2010

For the GATE-2011 Aspirants

I will soon launch a site with all the resources related to GATE CS preparation. First let me come out of the vicious admissions phase. Then I'll post all the resources I used, for the preparation online. Everything will be very well categorized subject wise.