Monday, 23 December 2013

Program to invert 'n' alternate bits of a number (Asked in APPLIED MATERIALS coding round)

// initial 30 = 11110
// final   11 = 01011

#include<stdio.h>
int invert_alternate_bit(int,int);
int main()
{
printf("NEW num : %d\n",invert_alternate_bit(30,3));
return 0;
}
int invert_alternate_bit(int num,int n)
{
int c = 0;
printf("OLD num : %d\n",num);
for(int i=1; i<= n ; i++)
{
c = c << 2;
c = c ^ 1;
}
num = num ^ c;
return num;
}

Sunday, 22 December 2013

Program to initialize the array as a pyramid of alphabets (Asked in APPLIED MATERIALS coding round)

#include<stdio.h>
void print_in(int,int,char);
void show(int,int);
void initialize(int,int);
char a[4][9];
int main()
{
char ch='A';
initialize(5,9);
print_in(0,4,ch);
show(5,9);
}
void print_in(int row,int col,char ch)
{
int count=1;
while(count<=25) // till Y
{
if(count==1)
{
a[row][col] = ch;
ch++;
}
if(count>1 && count<=4)
{
a[row][col] = ch;
col++;
ch++;
}
if(count>4 && count<=9)
{
a[row][col] = ch;
col++;
ch++;
}
if(count>9 && count<=16)
{
a[row][col] = ch;
col++;
ch++;
}
if(count>16 && count<=25)
{
a[row][col] = ch;
col++;
ch++;
}
if(count==1)
{
row++; // 1
col--;  // 3
}
if(count==4)
{
row++; // 2
col = col-4;// 2
}
if(count==9)
{
row++; // 3
col = col-6;// 1
}
if(count==16)
{
row++; // 4
col = col-8;// 0
}

count++;
}
}
void show(int row,int col)
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
printf("%c ",a[i][j]);
}
printf("\n");
}
}
void initialize(int row,int col)
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
a[i][j] = ' ';
}
}
}


Sample Output:
A
BCD
EFGHI
JKLMNOP
QRSTUVWXY

Wednesday, 18 December 2013

CISCO CERTIFIED NETWORKING WORKSHOP @CUSAT

ACM IIT Delhi Sponsored- National Network Security Championship (NNSC-2014) @ School of Engineering, Cochin University of Science and Technology
About NNSC

NNSC-2014 is National Network Security Championship with workshop series jointly being organized by Association for Computer Machinery-IIT Delhi and Network Bulls, Gurgaon. This championship, which is sponsored by ASIA’s Biggest Cisco Training Labs- Network Bulls - Gurgaon, will help students across the country to meet at same grounds and to learn about Cisco/Networking Technologies. 

Event Details

Workshop Date@CUSAT: 18 & 19 January, 2014.
Eligible Branches: ALL Branches (Expecting large participation from CSE, IT and EC) & ALL Semesters
Participation Fees:  1190
Seats: Limited seats according to the equipments available for each students. (Nearly 50). So Hurry, grab this golden opportunity.
Event Coordinator (Faculty): Mr. Vinod Kumar P.P. & Mr. V. Damodaran
Register: HERE

Stage 1 (WORKSHOP ROUND to be held at Zonal Centers)
A two day hands-on Network Implementation workshop will be held all across India
All the participants who want to participate in NNSC-2014 are required to attend the workshops at any Zonal Center and participate in the competition after the workshop.
The Duration of the Networking workshop will be of 2 Days (7-8 hrs each day).
The workshop will be delivered by Cisco Certified Professionals working with Network Bulls, Gurgaon. 

Stage 2 (ZONAL ROUND to be held at Zonal Center) 
Just after the workshop a Mega Competition of NNSC-2014 on the basis of the two day workshop will be held.
Winners will be awarded Certificate of Merit, and are required to participate in Final Rounds which will be held in the month of March 2014 at IIT Delhi. 

Stage 3 (FINAL ROUND to be held at IIT Delhi) 
Winners of all Zonal Centers will be competing against each other at NNSC-2014 in March 2014 in association with ACM-IIT Delhi.
Winner of this Final Round will win The National Network Security Champion title and will be awarded and honored by ACM-IIT Delhi with prizes worth 1 lakh rupees. 

For further details please visit:
Website: www.nnscindia.com
Facebook Page: 
www.facebook.com/nnscindia





Thursday, 12 December 2013

Program to find Maximum Run of a Character in a String (Asked in APPLIED MATERIALS coding round)

//program to find the maximum run count of a character

#include<stdio.h>
int main()
{
int count = 0, count_max = 0;
char ch[100],s;
int i=0;
gets(ch);
while(ch[i]!='\0')
{
s = ch[i];
while(ch[i]==s)
{
count++;
i++;
}
if(count_max<count)
{
count_max = count;
count = 0;
}
}
printf("MAX RUN = %d\n",count_max);
return 0;
}


Print Integer Using putchar only (Asked in APPLIED MATERIALS coding round)

//print integer using putchar only

#include<stdio.h>
void pr_int(int);
int main()
{
  int n;
scanf("%d",&n);
pr_int(n);
}
void pr_int(int n)
{
      if (n < 0)
     {
          putchar('-');
          n = -n;
     }
     if (n / 10 != 0)
          pr_int(n / 10);
    putchar((n % 10) + '0');
}

Monday, 2 December 2013

Program to Print itself

Language C.
Program name: printitself.c

CODE:

#include<stdio.h>
 int main()
 {
  FILE *file;
  char ch;
  file = fopen("printitself.c","r");
  while(( ch = fgetc(file) ) != EOF)
  {
  fputc(ch,stdout);
}
  fclose(file);
  return 0;
 }

Counting 1 up-to Counting of Number (ASKED IN GOOGLE RECRUITMENT)

// 13 -> 1 2 3 4 5 6 7 8 9 10 11 12 13 -> 6 occurences of 1 -> f(13)=6
// AIM: To find all n such that f(n)=n

#include<stdio.h>
int main()
{
int num,temp=0,i=0,count_of_ones=0;
while(1)
{ ++i;
num=i;
while(num>0)
{
temp=num%10;
if(temp==1)
count_of_ones++;
//printf("%d ",temp);
num=num/10;
}
if(i==count_of_ones)
printf("\ni = %d and count of ones = %d\n",i,count_of_ones);
}
return 0;
}


OUTPUT: (obtained during half-an-hour runtime on i3 processor)
i = 1 and count of ones = 1

i = 199981 and count of ones = 199981

i = 199982 and count of ones = 199982

i = 199983 and count of ones = 199983

i = 199984 and count of ones = 199984

i = 199985 and count of ones = 199985

i = 199986 and count of ones = 199986

i = 199987 and count of ones = 199987

i = 199988 and count of ones = 199988

i = 199989 and count of ones = 199989

i = 199990 and count of ones = 199990

i = 200000 and count of ones = 200000

i = 200001 and count of ones = 200001

i = 1599981 and count of ones = 1599981

i = 1599982 and count of ones = 1599982

i = 1599983 and count of ones = 1599983

i = 1599984 and count of ones = 1599984

i = 1599985 and count of ones = 1599985

i = 1599986 and count of ones = 1599986

i = 1599987 and count of ones = 1599987

i = 1599988 and count of ones = 1599988

i = 1599989 and count of ones = 1599989

i = 1599990 and count of ones = 1599990

i = 2600000 and count of ones = 2600000

i = 2600001 and count of ones = 2600001

i = 13199998 and count of ones = 13199998

i = 35000000 and count of ones = 35000000

i = 35000001 and count of ones = 35000001

i = 35199981 and count of ones = 35199981

i = 35199982 and count of ones = 35199982

i = 35199983 and count of ones = 35199983

i = 35199984 and count of ones = 35199984

i = 35199985 and count of ones = 35199985

i = 35199986 and count of ones = 35199986

i = 35199987 and count of ones = 35199987

i = 35199988 and count of ones = 35199988

i = 35199989 and count of ones = 35199989

i = 35199990 and count of ones = 35199990

i = 35200000 and count of ones = 35200000

i = 35200001 and count of ones = 35200001

i = 117463825 and count of ones = 117463825

i = 500000000 and count of ones = 500000000

i = 500000001 and count of ones = 500000001

i = 500199981 and count of ones = 500199981

i = 500199982 and count of ones = 500199982

i = 500199983 and count of ones = 500199983

i = 500199984 and count of ones = 500199984

i = 500199985 and count of ones = 500199985

i = 500199986 and count of ones = 500199986

i = 500199987 and count of ones = 500199987

i = 500199988 and count of ones = 500199988

i = 500199989 and count of ones = 500199989

i = 500199990 and count of ones = 500199990

i = 500200000 and count of ones = 500200000

i = 500200001 and count of ones = 500200001

i = 501599981 and count of ones = 501599981

i = 501599982 and count of ones = 501599982

i = 501599983 and count of ones = 501599983

i = 501599984 and count of ones = 501599984

i = 501599985 and count of ones = 501599985

i = 501599986 and count of ones = 501599986

i = 501599987 and count of ones = 501599987

i = 501599988 and count of ones = 501599988

i = 501599989 and count of ones = 501599989

i = 501599990 and count of ones = 501599990

i = 502600000 and count of ones = 502600000

i = 502600001 and count of ones = 502600001

i = 513199998 and count of ones = 513199998

i = 535000000 and count of ones = 535000000

i = 535000001 and count of ones = 535000001

i = 535199981 and count of ones = 535199981

i = 535199982 and count of ones = 535199982

i = 535199983 and count of ones = 535199983

i = 535199984 and count of ones = 535199984

i = 535199985 and count of ones = 535199985

i = 535199986 and count of ones = 535199986

i = 535199987 and count of ones = 535199987

i = 535199988 and count of ones = 535199988

i = 535199989 and count of ones = 535199989

i = 535199990 and count of ones = 535199990

i = 535200000 and count of ones = 535200000

i = 535200001 and count of ones = 535200001

i = 1111111110 and count of ones = 1111111110

i = -1323939513 and count of ones = -1323939513

i = -1000790756 and count of ones = -1000790756

i = -677641999 and count of ones = -677641999

i = 1839279971 and count of ones = 1839279971

i = 1839279972 and count of ones = 1839279972

i = 1839279973 and count of ones = 1839279973

i = 1839279974 and count of ones = 1839279974

i = 1839279975 and count of ones = 1839279975

i = 1839279976 and count of ones = 1839279976

i = 1839279977 and count of ones = 1839279977

i = 1839279978 and count of ones = 1839279978

i = 1839279979 and count of ones = 1839279979

i = 1839279980 and count of ones = 1839279980

i = -2001581512 and count of ones = -2001581512

then i stopped (manually halted the execution of infinite loop program : ctrl+Z)

DFA using Transition Table


PROGRAM Using Transition Table:

#include<stdio.h>
#include<string.h>
int main()
{
char state='A',str[50],input[20],inputstate[20],outputstate[20];
int j,i=0;
strcpy(input, "abcabcabcabcabc");
strcpy(inputstate, "AAABBBCCCDDDEEE");
strcpy(outputstate, "BCDBCDECDEEDEEE");
printf("Enter string : ");
scanf("%s",str);
while(str[i]!='\0')
{
for(j=0;j<15;j++)
{
if(inputstate[j] == state && input[j] == str[i])
{
state = outputstate[j];
break;
}
}
if(j==15)
{
state = 'F';
break;
}
i++;
}
if(state == 'A' || state == 'B' || state == 'C' || state == 'D' || state=='E' )
printf("Valid");
else
printf("InVALid");
return 0;
}

Evaluation of Boolean Expression (2013)

YACC:

%{
#include<stdio.h>
%}
%token DIGIT
%left '|'
%left '&'
%right '!'
%left '<' '>' '='

%%
input: input ans '\n' { printf("Result : %d\n",$2); }
| error '\n'         { printf("\n :( \n"); }
|
;
ans: ans '&''&' expr   { $$ = $1 && $4; }
| ans '|''|' expr                 { $$ = $1 || $4; }
| '!' ans                 { $$ = ! $2; }
| expr           { $$ = $1; }
;
expr: DIGIT '<' DIGIT { $$ = $1 < $3; }
| DIGIT '>' DIGIT         { $$ = $1 < $3; }
| DIGIT '<''=' DIGIT { $$ = $1 <= $4; }
| DIGIT '>''=' DIGIT { $$ = $1 >= $4; }
        | DIGIT '=''=' DIGIT { $$ = $1 == $4; }
| DIGIT         { $$ = $1; }
| '(' expr ')'         { $$ = $2; }
;
%%
int main()
{
printf("Enter boolean expression :\n ");
yyparse();
}
int yyerror(char *s)
{
printf("Error %s",s);
}


LEX:

%{
#include "y.tab.h"
%}
digit [0-9]+
op "&"|"|"|"!"|"<"|">"|"="
%%
{digit} { yylval = atoi(yytext); return DIGIT; }
{op} { return *yytext; }
[ \t] ;
\n { return *yytext; }
.
%%
int yywrap()
{
return 1;
}


HOW TO RUN:
$ yacc -d bool.y
$ lex bool.l
$ gcc lex.yy.c y.tab.h -o bool
$ ./bool

OUTPUT:
Enter boolean expression :
1&&1
Result : 1
1||0
Result : 1
(5<6)&&(8==8)
Result : 1

Recognition of C language statements ("for" statement)

NOTE: THE SAME PROGRAM CAN BE USED FOR ANY KIND OF C STATEMENT (JUST CHANGE THE GRAMMAR IN YACC FILE) LIKE: IF-ELSE, WHILE, STRUCTURE, DO-WHILE, SWITCH-CASE, FUNCTIONS ETC ETC...

YACC:

%{
#include<stdio.h>
%}
%token NUMBER ID KEY

%%
input: input def '\n' { printf("Valid\n"); }
| error '\n' { printf("NO\n"); }
|
;
def: KEY '(' exp ';' exp ';' exp ')' ';'
| KEY '(' exp ';' exp ';' exp ')' '\n' stmts
;
exp: ID '=' NUMBER
| ID '<' NUMBER
| ID '+''+'
|
;
stmts: '{' '\n' dec '\n' '}'
;
dec: KEY var ';'
;
var: var ',' ID
| ID
;
%%
int parser()
{
yyparse();
}
int yyerror(char *s)
{
printf(":( %s",s);
}


LEX:

%{
#include "y.tab.h"
%}
number [0-9]+
id [A-Za-z][A-Za-z0-9]*
key "for"|"int"|"float"|"char"|"double"
other "("|")"|"{"|"}"|";"|","|"="|"<"|"+"
%%
{key} { return KEY; }
{other} { return *yytext; }
{id} { return ID; }
{number} { return NUMBER; }
[ \t] ;
\n { return *yytext; }
.
%%
int main(int argc,char *argv[])
{
yyin = fopen(argv[1],"r");
parser();
fclose(yyin);
}
int yywrap()
{
return 1;
}


FILE: filefor

for ( i = 0 ; j < 10 ; k ++ )
{
int a,b,c,d;
}


HOW TO RUN:
$ yacc -d for.y
$ lex for.l
$ gcc lex.yy.c y.tab.c -o f
$ ./f filefor

OUTPUT:
Valid

Recognize Arithmetic Expression using Yacc

YACC

%{
#include<stdio.h>
%}
%token digit;

%%
input : program { printf("Valid"); }
;
program : program expr
|
;
expr :  digit
| expr '+' expr
| expr '-' expr
| expr '*' expr
| expr '/' expr
| expr '^' expr
;
%%
int main()
{
printf("Enter the expression : ");
yyparse();
return 0;
}
int yyerror(char *s)
{
printf("%s",s);
}


LEX

%{
#include "y.tab.h"
%}
%%
[0-9]+ { return digit; }
\n { return 0; }
[ \t] ;
. { return (int) yytext[0]; }
%%
int yywrap()
{
return 1;
}


HOW TO RUN:
$ yacc -d arith.y
$ lex arith.l
$ gcc lex.yy.c y.tab.h -o arith
$ ./arith

OUTPUT:
Enter the expression : 3+4-4
Valid
vijay@ubuntu:~/Desktop/lppractice$ ./arith
Enter the expression : 3344---
syntax error

Calculator using lex and yacc

YACC

%{
#include<stdio.h>
#include<math.h>
int sym[26];
%}
%token INTEGER VARIABLE
%left '+' '-'
%left '*' '/'
%right NEG
%right '^'
%%
program: program statement '\n'
|
;
statement: expr { printf("%d\n",$1); }
| VARIABLE '=' expr { sym[$1] = $3; }
;
expr: INTEGER
| VARIABLE { $$ = sym[$1]; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| '-' expr %prec NEG { $$ = -$2; }
| expr '^' expr { $$ = pow($1,$3); }
| '(' expr ')' { $$ = $2; }
;
%%
int main()
{
printf("Enter Expression: ");
yyparse();
return 0;
}
int yyerror(char *s)
{
printf("%s",s);
return 0;
}


LEX

%{
#include "y.tab.h"
#include<stdio.h>
%}
%%
[0-9]+ { yylval = atoi(yytext); return INTEGER; }
[a-z]  { yylval = *yytext; return VARIABLE; }
[-+()=*/^\n] { return *yytext; }
[ \t] ;
. yyerror("Invalid Character");
%%
int yywrap()
{
return 1;
}


HOW TO RUN:
$ yacc -d cal.y
$ lex cal.l
$ gcc lex.yy.c y.tab.c -lm -o cal
$ ./cal

OUTPUT:
Enter Expression: 2+3
5
1
1
e=1
f=3
g=e+f
g
4

Process X gives a file name and value n to process Y. Y has to copy first n lines of file into a new file and sent the file name back to X who display the content of new file. Implement using pipes.

#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int pid,p[2],p2[2],i,n,n2,num,check,a,j;
char buff1[100][100],buff2[100][100],ch,src[30],des[30];
FILE *source,*dest;
a = pipe(p);
if(a==-1)
{
perror("error pipe 1");
exit(1);
}
a = pipe(p2);
if(a==-1)
{
perror("error pipe 2");
exit(1);
}
pid = fork();
switch(pid)
{
case -1: perror("fork");
exit(1);
break;
case 0:
read(p[0],buff2,sizeof(buff2));
printf("In child process (PID : %d ) \n",pid);

int l,i;
strcpy(src,buff2[0]);
l = (int)buff2[1][0] - 48; //ASCII of 0 is 48
printf("\nsource file name : %s",src);
printf("\nNmber of line : %d",l);
printf("\nEnter destination file name : ");
gets(des);
source = fopen(src,"r");
dest = fopen(des,"w");
i=1;
l=2; //dummy
while(i<=l)
{
while( (ch=fgetc(source)) != '\n')
{
fputc(ch,dest);
}
fputc('\n',dest);
i++;
}
strcpy(buff1[0],des);
write(p2[1],buff1,sizeof(buff1));
exit(1);
break;

default: printf("In parent process (PID: %d) \n",pid);

printf("enter file name : ");
scanf("%s",buff1[0]);

printf("enter line limit : ");
scanf("%s",buff1[1]);

write(p[1],buff1,sizeof(buff1));
waitpid(pid,NULL,0);
printf("In parent process (PID: %d) \n",pid);
read(p2[0],buff2,sizeof(buff2));

printf("\nnew file created %s ",buff2[0]);

break;
}
close(p[0]);
close(p[1]);
close(p2[0]);
close(p2[1]);
return 0;
}

X sends N numbers to Y who select prime numbers and send them to Z. Z send the sum of primes to X who displays the result. Implement IPC using pipes. X,Y,Z are processes.

#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int pid,pid1,p[2],p2[2],p3[2],buff1[100],buff2[100],i,n,n2,num,check,a,j;
int sum=0;
printf("Enter limit : ");
scanf("%d",&n);
n2=0;
a = pipe(p);
if(a==-1)
{
perror("error pipe 1");
exit(1);
}
a = pipe(p2);
if(a==-1)
{
perror("error pipe 2");
exit(1);
}
a = pipe(p3);
if(a==-1)
{
perror("error pipe 3");
exit(1);
}
pid = fork();
switch(pid)
{
case -1: perror("fork");
exit(1);
break;
case 0: n2 = read(p2[0],buff2,sizeof(buff2));
printf("In child process Z (PID : %d ) \n",pid);
n2 = n2/sizeof(int);

printf("value of n2: %d",n2);
for(i=0;i<n2;i++)
{
printf("\nPrime numbers %d : %d",i+1,buff2[i]);
sum = sum + buff2[i];
}
buff1[0] = sum;
write(p3[1],buff1,sizeof(int));
exit(1);
break;

default:
pid1 = fork();
switch(pid1)
{
case -1: perror("fork");
exit(1);
break;

case 0 :
read(p[0],buff2,sizeof(buff2));
printf("In child process Y (PID1 : %d ) \n",pid1);
for(i=0;i<n;i++)
{
int flag=1;
num = buff2[i];
if(num < 2)
{
flag=0;
}
else
{
check = sqrt(num);
for(j=2;j<=check;j++)
{
if(num%j == 0)
{
flag=0;
break;
}
}
}
if(flag==1)
{
buff1[n2] = num;
n2++;
}
}
write(p2[1],buff1,n2*sizeof(int));
exit(1);
break;
default: printf("In parent process X (PID: %d) \n",pid1);
for(i=0;i<n;i++)
{
printf("enter element %d : ",i+1);
scanf("%d",&buff1[i]);
}
write(p[1],buff1,n*sizeof(int));
waitpid(pid1,NULL,0);
printf("\nIn parent process (PID: %d) \n",pid1);
read(p3[0],buff2,sizeof(buff2));
printf("\nsum : %d\n",buff2[0]);
}
break;
}
close(p[0]);
close(p[1]);
close(p2[0]);
close(p2[1]);
close(p3[0]);
close(p3[1]);
return 0;
}


OUTPUT:
$ gcc program.c -lm -o prog (NOTE: -lm is important to compile math functions like sqrt)
$ ./prog

Enter limit : 3
In parent process X (PID: 4773)
enter element 1 : 1
enter element 2 : 2
enter element 3 : 5
In child process Y (PID1 : 0 )
In child process Z (PID : 0 )
value of n2: 2
Prime numbers 1 : 2
Prime numbers 2 : 5
In parent process (PID: 4773)
sum : 7

UDP Client-Server Chat Session

SERVER:

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define BUFLEN 512
#define PORT 9930

void err(char *str)
{
    perror(str);
    exit(1);
}

int main(void)
{
    struct sockaddr_in my_addr, cli_addr;
    int sockfd, i;
    socklen_t slen=sizeof(cli_addr);
    char buf[BUFLEN];

    if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
      err("socket");
    else
      printf("Server : Socket() successful\n");

    bzero(&my_addr, sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(PORT);
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
   
    if (bind(sockfd, (struct sockaddr* ) &my_addr, sizeof(my_addr))==-1)
      err("bind");
    else
      printf("Server : bind() successful\n");

    while(1)
    {
        if (recvfrom(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&cli_addr, &slen)==-1)
            err("recvfrom()");
        printf("Received packet from %s:%d\nData: %s\n\n",
               inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port), buf);
    }

    close(sockfd);
    return 0;
}


CLIENT:

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define BUFLEN 512
#define PORT 9930

void err(char *s)
{
    perror(s);
    exit(1);
}

int main(int argc, char** argv)
{
    struct sockaddr_in serv_addr;
    int sockfd, i, slen=sizeof(serv_addr);
    char buf[BUFLEN];

    if(argc != 2)
    {
      printf("Usage : %s <Server-IP>\n",argv[0]);
      exit(0);
    }

    if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
        err("socket");

    bzero(&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    if (inet_aton(argv[1], &serv_addr.sin_addr)==0)
    {
        fprintf(stderr, "inet_aton() failed\n");
        exit(1);
    }

    while(1)
    {
        printf("\nEnter data to send(Type exit and press enter to exit) : ");
        scanf("%[^\n]",buf);
        getchar();
        if(strcmp(buf,"exit") == 0)
          exit(0);

        if (sendto(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&serv_addr, slen)==-1)
            err("sendto()");
    }

    close(sockfd);
    return 0;
}


HOW TO RUN:
1: open terminal
2: gcc  server.c
3: ./a.out

4: open another terminal
5: gcc client.c
6: ./a.out <server-ip> (check the ip of the machine and put here)

OUTPUT:
SERVER SIDE
$ ./a.out
Server : Socket() successful
Server : bind() successful
Received packet from 192.168.0.3:37555
Data: hi

Received packet from 192.168.0.3:37555
Data: hello

Received packet from 192.168.0.3:37555
Data: i m client

CLIENT SIDE
$ ./a.out 192.168.0.3
Enter data to send(Type exit and press enter to exit) : hi

Enter data to send(Type exit and press enter to exit) : hello

Enter data to send(Type exit and press enter to exit) : i m client

TCP Client-Server Chat Session

SERVER:

#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>
#define MAX 80
#define PORT 43454
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for(;;)
{
bzero(buff,MAX);
read(sockfd,buff,sizeof(buff));
printf("From client: %s To client : ",buff);
bzero(buff,MAX);
n=0;
while((buff[n++]=getchar())!='\n');
write(sockfd,buff,sizeof(buff));
if(strncmp("exit",buff,4)==0)
{
printf("Server Exit...\n");
break;
}
}
}
int main()
{
int sockfd,connfd,len;
struct sockaddr_in servaddr,cli;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(PORT);
if((bind(sockfd,(SA*)&servaddr, sizeof(servaddr)))!=0)
{
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
if((listen(sockfd,5))!=0)
{
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len=sizeof(cli);
connfd=accept(sockfd,(SA *)&cli,&len);
if(connfd<0)
{
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");
func(connfd);
close(sockfd);
}


CLIENT:

#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#define MAX 80
#define PORT 43454
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for(;;)
{
bzero(buff,sizeof(buff));
printf("Enter the string : ");
n=0;
while((buff[n++]=getchar())!='\n');
write(sockfd,buff,sizeof(buff));
bzero(buff,sizeof(buff));
read(sockfd,buff,sizeof(buff));
printf("From Server : %s",buff);
if((strncmp(buff,"exit",4))==0)
{
printf("Client Exit...\n");
break;
}
}
}

int main()
{
int sockfd,connfd;
struct sockaddr_in servaddr,cli;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(PORT);
if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))!=0)
{
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
func(sockfd);
close(sockfd);
}


HOW TO RUN:
1: open terminal
2: gcc server.c
3: ./a.out

4: open another terminal
5: gcc client.c
6: ./a.out

OUTPUT:
SERVER SIDE
$ gcc server.c
$ ./a.out
Socket successfully created..
Socket successfully binded..
Server listening..
server acccept the client...
From client: hi
To client : hello
From client: exit
To client : exit
Server Exit...
$

CLIENT SIDE
$ gcc client.c
$ ./a.out
Socket successfully created..
connected to the server..
Enter the string : hi
From Server : hello
Enter the string : exit
From Server : exit
Client Exit...



Producer-consumer problem

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/sem.h>
#define EMPTY 0
#define FULL 1
#define MUTEX 2
#define SIZE 10
void up(int sem_id,int sem_num,struct sembuf *semaphore){
  semaphore->sem_num=sem_num;
   semaphore->sem_op=1;
   semaphore->sem_flg=0;
   semop(sem_id,semaphore,1);
}
void down(int sem_id,int sem_num,struct sembuf *semaphore){
   semaphore->sem_num=sem_num;
   semaphore->sem_op=-1;
   semaphore->sem_flg=0;
   semop(sem_id,semaphore,1);
}
void initsem(int sem_id,int sem_num,int val){
   union semnum{
      int val;
      struct semid_ds *buf;
      unsigned short *array;
   }argument;
   argument.val=val;
  semctl(sem_id,sem_num,SETVAL,argument);
}
int main(){
   key_t shm_key=1234,sem_key=3456;
   int shm_id,sem_id;
   int *shm;
   struct sembuf semaphore;
   shm_id=shmget(shm_key,SIZE+1,IPC_CREAT|0666);
   sem_id=semget(sem_key,3,IPC_CREAT|0666);
   shm=shmat(shm_id,NULL,0);
  shm[0]=0;
  initsem(sem_id,EMPTY,SIZE);
   initsem(sem_id,FULL,0);
  initsem(sem_id,MUTEX,1);
   if(fork()==0){
      while(1){
         int item,i;
         sleep(2);
         down(sem_id,FULL,&semaphore);
         down(sem_id,MUTEX,&semaphore);
         item=shm[1];
         for(i=1;i<shm[0];i++)
           shm[i]=shm[i+1];
         shm[0]--;
         printf("\nConsumed %d",item);
         up(sem_id,MUTEX,&semaphore);
         up(sem_id,EMPTY,&semaphore); 
      }
  }
  else{
      while(1){
         int item=random()%10;
         sleep(1);
         down(sem_id,EMPTY,&semaphore);
         down(sem_id,MUTEX,&semaphore);
         shm[++shm[0]]=item;
         printf("\nProduced %d",item);
         up(sem_id,MUTEX,&semaphore);
         up(sem_id,FULL,&semaphore); 
      }
   }
}