C/C++ Linux Interview Questions asked in real IT companies in India

Watch this space for coming soon C++ Class object data members constructor destructor abstraction encapsulation inheritance operator over loading polymormophism run time and static morphism virtual base class virtual function virtual keyword private protected public access specified template exception handling STL default constructor copy constructor destructor overloaded assignment operator shallow vs deep constructor malloc vs new delete vs free heap and static memory dangling pointer wild pointer crash hang static dynamic reinterpret cast pointers array reference.

C++ program to implement:Default constructor, One argument constructor, Copy constructor, overloaded assignment operator, destructor and overload + operator to concatenate two strings in a single program.

How to use array of structure in C Linux Code.

How to enter details of 10 (multiple) employee ? Answer is array of employee structures.
#include<stdio.h>
#include<memory.h>
struct employee
{
int id;
char name[20];
//int age;
};

int main()
{
int i;
struct employee arr[3];
for(i=0;i<3;i++)
{
printf("Enter details of employess:");
scanf("%d%s",&arr[i],arr[i].name);
}
printf("Employee details:\n");
for(i=0;i<3;i++)
{
printf("id=%d, name=%s\n",arr[i].id, arr[i].name);
}
return 0;
}
/*******OUTPUT
Enter details of employess:1
Leal
Enter details of employess:2
Mitra
Enter details of employess:333
Jesus
Employee details:
id=1, name=Leal
id=2, name=Mitra
id=333, name=Jesus
*****************/
//Display structure details based on search conditions
//students's name and roll number should be stored in structure
//array of 10 student structure
//take input and display
//displaye the student detail whose roll number is entered
#include<stdio.h>
#define SIZE 2
struct student
{
char name[20];
int roll;
};
struct student arr[SIZE];//needs global
int i;
int rollSearch;

void add();
void disp();
void search();
int main()
{
//Array of 5 students
//struct student arr[5];//needs global
//enter student details
add();
//display students details
disp();
//display details of student whose roll number is entered
search();
return 0;
}
void add()
{
for(i=0;i<SIZE;i++)
{
printf("Enter name of student %d:",i+1);
scanf("%s",arr[i].name);
printf("Enter roll of student %d:",i+1);
scanf("%d",&arr[i].roll);
}
}
void disp()
{
printf("*************Student Details***************\n");
for(i=0;i<SIZE;i++)
{
printf("Name of student %d is:%s\n",i+1,arr[i].name);
printf("Roll of student %d is:%d\n",i+1,arr[i].roll);
}
}
void search()
{
int flag=0;
printf("*************Search Result***************\n");
printf("Enter Roll of whose details you want:");
scanf("%d",&rollSearch);
for(i=0;i<SIZE;i++)
{
if(arr[i].roll==rollSearch)//mind the syntax roll[i].roll
{
flag=1;
printf("Name of student %d is:%s\n",i+1,arr[i].name);
printf("Roll of student %d is:%d\n",i+1,arr[i].roll);
}
}
if(flag==0)
printf("Roll Number does not exist.\n");
}
/*Output:
Enter name of student 1:Leal
Enter roll of student 1:100
Enter name of student 2:Mitra
Enter roll of student 2:200
Enter name of student 3:Ram
Enter roll of student 3:300
Enter name of student 4:Raheem
Enter roll of student 4:400
Enter name of student 5:yeshu
Enter roll of student 5:500
*************Student Details***************
Name of student 1 is:Leal
Roll of student 1 is:100
Name of student 2 is:Mitra
Roll of student 2 is:200
Name of student 3 is:Ram
Roll of student 3 is:300
Name of student 4 is:Raheem
Roll of student 4 is:400
Name of student 5 is:yeshu
Roll of student 5 is:500
*************Search Result***************
Enter Roll of whose details you want:200
Name of student 2 is:Mitra
Roll of student 2 is:200
*/

How to access nested structure members in C C++ Linux

#include<stdio.h>
#include<memory.h>
struct employee
{
int id;
char name[10];
struct dob
{
int day;
int month;
int year;
}d;
};

int main()
{
struct employee e1;
//struct dob dd;//can decalre but cant use
e1.id=1000;
strcpy(e1.name,"LealMitra");
e1.d.day=10;
e1.d.month=7;
e1.d.year=2014;

printf("Employee details:\n");
printf("id=%d, name=%s, dob=%d-%d-%d \n",e1.id, e1.name, e1.d.day,e1.d.month,e1.d.year);

return 0;
}
/****************OUTPUT
Employee details:
id=1000, name=LealMitra, dob=10-7-2014
*****************/

How to Initialize structure member variables in C C++

Ways of initializing a structure in C and C++. How not to do mistake in initializing structures.
#include<stdio.h>
#include<memory.h>
struct employee
{
int id;
char name[20];
//Note that below ways of initializing structure is error.
//int id=10;//erro:because memory is not allocated for structure here.
//strcpy(name,"Ram");//error for same reason.
};

int main()
{
//one way of initializing structure.
struct employee e1={1000,"Leal"};//one way of initializing structure.
printf("Employee details:\n");
printf("id=%d, name=%s\n",e1.id,e1.name);


//Another way of initializing structure.
struct employee e2;
e2.id=1001;
strcpy(e2.name,"Mitra");
printf("\nEmployee details:\n");
printf("id=%d, name=%s\n",e2.id,e2.name);

//Yet another way of initializing  structure.
struct employee e3;
printf("Enter id :\n");
scanf("%d",&e3.id);
printf("Enter name :\n");
scanf("%s",&e3.name);
printf("\nEmployee details:\n");
printf("id=%d, name=%s\n",e3.id,e3.name);
return 0;
}
/******* OUTPUT
@ubuntu:~/headHunt$ gcc structureInitialization.c 
structureInitialization.c: In function ‘main’:
structureInitialization.c:30:1: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat]
@ubuntu:~/headHunt$ gcc structureInitialization.c 
structureInitialization.c: In function ‘main’:
structureInitialization.c:30:1: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat]
@ubuntu:~/headHunt$ ./a.out 
Employee details:
id=1000, name=Leal

Employee details:
id=1001, name=Mitra
Enter id :
200
Enter name :
blog

Employee details:
id=200, name=blog
@ubuntu:~/headHunt$ 
*****************/

Writing and Reading File through C Linux Code

/* Writing to a file. Reading from a file */
#include<stdio.h>
int main()
{
    //writing to file
    FILE *fpw;
    fpw=fopen("1.txt","w+");
    fputs("Hello India\n",fpw);
    fclose(fpw);

    //Reading from file
    char buff[20];
    FILE *fpr;
    fpr=fopen("1.txt","r");
    fgets(buff,20,(FILE*)fpr);
    printf("%s\n",buff);
    fclose(fpr);
    return 0;
}
/*
 Hello India
 */

---------
/*
 Writing to a file
 Reading from a file
 Writing to another file
 */
#include<stdio.h>
int main()
{
    //writing to file
    FILE *fpw;
    fpw=fopen("1.txt","w+");
    fputs("Hello India\n",fpw);
    fclose(fpw);

    //Reading from file
    char buff[20];
    FILE *fpr;
    fpr=fopen("1.txt","r");
    fgets(buff,20,(FILE*)fpr);
    printf("%s\n",buff);

        //Writing to another file
    FILE *fpo;
    fpo=fopen("22.txt","w+");
    fputs(buff,fpo);
        //fprintf(fpo,"%s",buff);
    fclose(fpr);
    fclose(fpr);
    return 0;
}
/*
 Hello India
 */

---------

/*
 Writing and reading to and from file
 */
#include <stdio.h>
int main()
{
    /*Writing to a file*/
    FILE *fp;
    fp = fopen("test.txt", "w+");
    fprintf(fp, "This is testing for fprintf...\n");
    fputs("This is testing for fputs...\n", fp);
    fclose(fp);

    /*Reading from a file*/
    FILE *fp1;
    char buff[255];
    fp1 = fopen("test.txt", "r");
    fscanf(fp1, "%s", buff);//upto space
    printf("1 : %s\n", buff );

    fgets(buff, 255, (FILE*)fp1);//upto new line
    printf("2: %s\n", buff );

    fgets(buff, 255, (FILE*)fp1);//last line
    printf("3: %s\n", buff );
    fclose(fp1);

    return 0;
    }
/*
1 : This
2:  is testing for fprintf...
3: This is testing for fputs...
 */
/*
 The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. 
It copies the read string into the buffer buf, appending a null character to terminate the string.
We can also use int fscanf(FILE *fp, const char *format, ...) function to read strings froma file but it stops reading after the first space character encounters.

Sorting Numbers in File and Writing to Other File Through C Linux Code

/*Code for taking numbers from an input file sort it and write it to another output file.
  Input file contains 216543 
 Output file contains 123456 */
#include<stdio.h>
int main()
{
        FILE *f1,*f2;
        int i,j,temp,v[6],ch;
        f1=fopen("data.in","r");
        f2=fopen("data.out","w+");

        for(i=0;i<6;i++)
                fscanf(f1,"%d",&v[i]);

        for(i=0;i<6;i++)
        {
                for(j=i+1;j<6;j++)
                {
                        if(v[i]>v[j])
                        {
                                temp=v[i];
                                v[i]=v[j];
                                v[j]=temp;
                        }
                }
        }
        for(i=0;i<6;i++)
                fprintf(f2,"%d\n",v[i]);

        close(f1);
        close(f2);
        return 0;
}

------------
/*
Code for taking numbers from an input file sort it and write it to an output file.
   Input file 216543
   Output file 123456
by counting the number of lines  
*/
#include<stdio.h>
int main()
{
        FILE *f1,*f2;
        int i,j,temp,v[10],ch,n=0;
        f1=fopen("data.in","r");
        f2=fopen("data.out","w");

char line[1024];

n=0;
while(fgets(line,sizeof(line),f1)!=NULL)
n++;
/*set the file pointer to beginning*/
fseek(f1,0,SEEK_SET);


        for(i=0;i<n;i++)
                fscanf(f1,"%d",&v[i]);

        for(i=0;i<n;i++)
        {
                for(j=i+1;j<n;j++)
                {
                        if(v[i]>v[j])
                        {
                                temp=v[i];
                                v[i]=v[j];
                                v[j]=temp;
                        }
                }
        }
        for(i=0;i<n;i++)
                fprintf(f2,"%d\n",v[i]);

        close(f1);
        close(f2);
        return 0;
}

Creating Shared and Static Library in C by understanding difference between them

Difference between static(.a) and shared library(.so) ?
Archived objects(.a) i.e. static libraries are compiled into the program itself. When multiple programs/application uses the static library then multiple times same pre-compiled functions in that library gets included in to the program as well as in the main memory so size of application increases.
But shared library over comes this issue.
Shared Objects (.so) i.e. shared libraries are compiled separately and only reference/linked given such that only required functions are loaded into the memory at run time. so small size of the application as it does not contains the function code.

steps to create static library(archives) .a

step1:writing the function in library as library is nothing but set of pre compiled functions
we use funcInt(int i) and funcChar(char *charp)

/*funcInt.c:first function to be precompiled for our library*/
#include<stdio.h>

void funcInt(int i)
{
printf("\nint version library function called.\n");
}

/*funcChar:Second function to be archived in our library*/
#include<stdio.h>

void funcChar(char *charp)
{
printf("\nchar version library function called.\n");
}


step2:creating the objects files
compile the above functions with -c option which will create only object file and avoid creation of executable program.
(without -c above functions will not compile also as no main function)
gcc -c funcInt.c funcChar.c

ls *.o
it will show the created object files :
funcChar.o  and  funcInt.o

step3:creating the static library say ourlibrary by precompiling these functions and archiving it.
according to naminf=g convention it will be prefixed with lib and post fixed with .a
ar -crv libourlibrary.a funcInt.o funcChar.o
Note that lib prefixing is must.

step4: writing header file say ourheader.h having declarion of these function in ourlibrary
any application/program want to use this library must include this header file.

/*header file to be included for uing the created library*/
#include<stdio.h>
void funcInt(int i);
void funcChar(char *charp);

step5: using the created library in main funcions say funcMain.c
create the calling function in main and include the header file containing the library function declaration
#include<stdio.h>
#include "ourheader.h"/*header file to use static libraries created above*/

int main()
{
//calling the library function created
funcChar("calling the library function funcChar.");
return 0;
}

gcc -o programexecutable funcMain.c funcChar.c
OR
gcc -o programexecutable funcMain.o libourlibrary.a
OR
gcc -o programexecutable funcMain.o -lourlibrary


ms@ubuntu:~/libraryCreation$ ar -crv libourlib.a funcChar.o funcInt.o
a - funcMain.o
a - funcChar.o
a - funcInt.o
ms@ubuntu:~/libraryCreation$ gcc -o m funcMain.o libourlib.a
ms@ubuntu:~/manoj/libraryCreation$ ./m
char version library function called.

--------------
Summary:
Static Library
1. Static libraries are compiled into the program itself.
2. Program Size increases.
3.  Every  program  has  its  own  static library.

Shared Library:
1.  Shared  libraries  are  compiled separately  and  referenced  by  the program.
2.  Program  size  is  smaller  but  shared libraries are required at the run time.
3.  Shared  library  has  only  one  copy and referenced by different programs.

Process to create static library
1.  gcc -­c mylibrary.c -­o mylibrary.o
2.  ar rcs libmylibrary.a mylibrary.o

Process to create shared library
1.  gcc -­c -­fPIC mylibrary.c -­o mylibrary.o
2.  gcc ­-shared -­Wl,­soname,libmylibrary.so.1 -­o libmylibrary.so.1.0.1 mylibrary.o

Tar the source (if needed) using this command
tar-zcf libmylibrary.tar.gz libmylibrary/

How to use static library :
Compile :gcc -­static test.c -­L. ­-lmylibrary -­o statexec
Run : ./statexec

How to use dynamic/shared library :
            Compile :gcc test.c -­o dynamicexec -­L. –lmylibrary
            Run : ./dynamicexec

You May Like:

 

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network

C Linux Code for multi threaded socket client/Server file sharing ftp

POSIX Mutex Implementation C Program in Linux

/*POSIX MUTEX implementationstwo threads takes 2 strings and combined.Two thrads trying to read two strings from the user and combined it.If mutex not used then it may be that second string  may be read by other thread.Here, with mutex we are sharing the keyboard effectively.mutex here ensures that which ever thread gets the mutex lock will read the both strings from the user keyboard.*/#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
pthread_mutex_t mlock;
pthread_t th1;
void *threadFunc1(void *arg);
int main()
{
        char str1[80];
        char str2[40];
        if(pthread_mutex_init(&mlock,NULL)!=0)
        {
                printf("Mutext creation failed,\n");
                exit(1);
        }
        pthread_create(&th1,NULL,threadFunc1,NULL);
        while(1)
        {
                pthread_mutex_lock(&mlock);
                printf("MAIN THREAD Enter 2 strings:\n");
                fgets(str1,40,stdin);
                fgets(str2,40,stdin);
                strcat(str1,str2);
                printf("In main Combined String is:%s\n",str1);
                        pthread_mutex_unlock(&mlock);
        }
        return 0;
}
void* threadFunc1(void *arg)
{
        char str1[80];
        char str2[80];
        while(1)
{
pthread_mutex_lock(&mlock);
        printf("thread function Enter 2 strings:\n");
        fgets(str1,40,stdin);
        fgets(str2,40,stdin);
        strcat(str1,str2);
        printf("In Thread function Combined String is:%s\n",str1);
                pthread_mutex_unlock(&mlock);
}
}
/*
MAIN THREAD Enter 2 strings:
aaaa
bbbbb
In main Combined String is:aaaa
bbbbb

MAIN THREAD Enter 2 strings:
ssss sss
dddd
In main Combined String is:ssss sss
dddd

thread function Enter 2 strings:
gggg gggg
fff fff
In Thread function Combined String is:gggg gggg
fff fff

MAIN THREAD Enter 2 strings:
sdfg
hhhhj
In main Combined String is:sdfg
hhhhj

MAIN THREAD Enter 2 strings:

*/

POSIX Semaphore Implementation Example code in C on Linux

/*POSIX semaphore Implementation for thread synchronization.
Accept string and convert its case. If semaphore is not used chances are there that input of one thread gets converted by other thread and unwanted result.
*/
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<string.h>

#define MAXMSGLEN 256

sem_t sem1;
char msg1[MAXMSGLEN];
char msg2[MAXMSGLEN];
sem_t sem2;

void* threadFunc1(void *arg);
void toggleCase(char *buf);

int main()
{
        pthread_t thread1;
        char argmsg1[]="Thread1: ";
        int res;
        int thNum;

        res=sem_init(&sem1,0,0);
        res=sem_init(&sem2,0,0);

        res=pthread_create(&thread1,NULL,threadFunc1,argmsg1);

        while(1)
        {
                printf("Print message to send:\n");
                fgets(msg1,MAXMSGLEN,stdin);
                sem_post(&sem1);
                /******wait for response****/
                sem_wait(&sem2);
                printf("Resp message: %s \n",msg2);
        }
        return 0;
}
void* threadFunc1(void *arg)
{
        printf("I am :%s \n",arg);
        while(1)
        {
                sem_wait(&sem1);
                strcpy(msg2,msg1);
                toggleCase(msg2);
                sem_post(&sem2);
        }
}
void toggleCase(char *str)
{
        while(*str)
        {
                if(isupper(*str))
                        *str=tolower(*str);
                else if(islower(*str))
                        *str=toupper(*str);
                str++;
        }
}
/*
   Print message to send:
   I am :Thread1:
   aaaaa
   Resp message: AAAAA
Print message to send:
   bbbbb
   Resp message: BBBBB

   Print message to send:
   CCCCC
   Resp message: ccccc

   Print message to send:
   asdfZXCV
   Resp message: ASDFzxcv

   Print message to send:

   WITHOUT sem OP is:
   -----------------=-
   Print message to send:
   I am :Thread1:
   qqqqqqqq
   Resp message:
   Print message to send:
   aaaa
   Resp message: QQQQQQqq

   Print message to send:
   ddd
   Resp message: AAAa

   Print message to send:
   aaaa
   Resp message: ddd

   Print message to send:
   ---------------------

*/

POSIX Mutex Implementation C Program in Linux


IPC and Sockets Programs in C in Linux Platform

IPC: Inter Process Communication means exchanging messages or data between processes.
Processes can reside on same machine or in separate machines in a network according to which IPC or Socket is used.

Traditional IPC:
1. Pipes:Only related Processes can communicate as only child can share the file descriptor of parent.
2. Fifo(named pipes): since fifo has name so it can be opened by other processes for read write.

System V IPC:
1.Message Queue
2.Semaphore
3.Shared Memory

Socket Programming/ Network programming:
Traditional and System V IPC can be used by processes whicce run on the same machine not over the Network.For the Processes that run on different machines "socket" is used. Socket can be thought of extended System V IPC. Socket Can be thought of end point of a communication channel.
Networking Programming generally follow Client Server model. Server runs forever and waits for requests from clients.Client requests for services from server. Server process the request and send to client.Browsers can be thought of http clients that requests for html pages from http/web servers.

In C programming generally Berkeleys Socket APIs are used for socket programming. Other APIS like TLI(Transport Layer Interface of system V) are also available.

Socket System Calls:

Used by Serverer           Used by client
socket()                  Socket()
bind()
listen()
accept()<----------------------connect()
read/recv/recfrom<---------write/send/sendto
write/send/sendto---------->read/recv/recfrom
close()           close()

Server Program:
First step of any network program is to create a socket using socket() system call.And, initialize the server_address with family,IP and Port.
Then created server is bind() with the server_Address and port on which then server listen() for incoming connections from client. Then server
accept() a connection from client and then read()/write() and finally close() the socket.
Client Program:
Client Program also start with creating a socket() and initialization of server socket with family,IP and port.Then connect() with the server and write()/read() and finally close() the socket.

Note:Apart from read() and write() in socket programming send()/recv() with tcp and sendto()/recvfrom() with udp can also be used.

Note :System V IPC ie message queue, semaphore and shared memory can not use read write as they are not implemented by the kernel.
Message Queue uses below API:
msgget()
msgctl()
msgsnd()
msgrcv()
Shared Memory Uses below api:
shmget()
shmctl()
shmat()
shmdt()
Semaphore uses below api:
semget()
semctl()
semop()

System V semaphore are complex so generally they are wrapped around pthread like semaphore functions.

You may like:

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network

C Linux Code for multi threaded socket client/Server file sharing ftp

POSIX Semaphore Implementation Example code in C on Linux

POSIX Mutex Implementation C Program in Linux


Threaded Concurrent echo TCP Server Code in C in Linux Platform

//TCP SERVER Concurrent:muliple clients can be handled by this server
//Now second client no need to wait for first client to close by finishing its task.
//This server now handles 5 clients simueltaneously. i.e. Now Upto 5 clients simueltaneously can send and receive messages from this server.
//Here concurrency is achieved  by creating a new thread which process  each new client while parent continues to accepting new connections.


#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define MAXSZ 100
void* funcTask(void *arg);

int main()
{
int sockfd;//to create socket
int newsockfd;//to accept connection

struct sockaddr_in serverAddress;//server receive on this address
struct sockaddr_in clientAddress;//server sends to client on this address

int n;
char msg[MAXSZ];
int clientAddressLength;
int pid;
pthread_t serverThread;

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=htonl(INADDR_ANY);
serverAddress.sin_port=htons(PORT);

//bind the socket with the server address and port
bind(sockfd,(struct sockaddr *)&serverAddress, sizeof(serverAddress));

//listen for connection from client
listen(sockfd,5);

while(1)
{
//parent process waiting to accept a new connection
printf("\n*****server waiting for new client connection:*****\n");
clientAddressLength=sizeof(clientAddress);
newsockfd=accept(sockfd,(struct sockaddr*)&clientAddress,&clientAddressLength);
printf("connected to client: %s\n",inet_ntoa(clientAddress.sin_addr));

pthread_create(&serverThread,NULL,&funcTask,(void *)newsockfd);
}

return 0;
}
void* funcTask(void *arg)
{
int n;
int newsockfd=(int)arg;
char msg[MAXSZ];

pthread_detach(pthread_self());
while(1)
{
n=recv(newsockfd,msg,MAXSZ,0);
if(n==0)
{
close(newsockfd);
break;
}
msg[n]=0;
send(newsockfd,msg,n,0);

printf("Receive and set:%s\n",msg);
}
close(newsockfd);
}
/*
ms@ubuntu:~/ipc_socket$ gcc server.c -o s -lpthread
ms@ubuntu:~/ipc_socket$ ./s

 *****server waiting for new client connection:*****
 connected to client: 127.0.0.1

 *****server waiting for new client connection:*****
 Receive and set:India

 Receive and set:is

 Receive and set:Great

 connected to client: 127.0.0.1

 *****server waiting for new client connection:*****
 Receive and set:The

 Receive and set:USA

 */
/***************CLIENT ITERATIVE*******************/

#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define SERVER_IP "127.0.0.1"
#define MAXSZ 100
int main()
{
int sockfd;//to create socket

struct sockaddr_in serverAddress;//client will connect on this

int n;
char msg1[MAXSZ];
char msg2[MAXSZ];

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=inet_addr(SERVER_IP);
serverAddress.sin_port=htons(PORT);

//client  connect to server on port
connect(sockfd,(struct sockaddr *)&serverAddress,sizeof(serverAddress));
//send to sever and receive from server
while(1)
{
printf("\nEnter message to send to server:\n");
fgets(msg1,MAXSZ,stdin);
if(msg1[0]=='#')
break;

n=strlen(msg1)+1;
send(sockfd,msg1,n,0);

n=recv(sockfd,msg2,MAXSZ,0);

printf("Receive message from  server::%s\n",msg2);
}

return 0;
}
/*
client:
ms@ubuntu:~/ipc_socket$ gcc tcpclient.c -o c
ms@ubuntu:~/ipc_socket$ ./c

Enter message to send to server:
India
Receive message from  server::India

Enter message to send to server:
IS
Receive message from  server::IS

Enter message to send to server:
Great
Receive message from  server::Great

Enter message to send to server:
*/

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network


C Linux Code for multi threaded socket client/Server file sharing ftp


Concurrent Server handling Multiple Clients Code in C in Linux Platform

//TCP SERVER Concurrent: multiple clients can be handled by this server
//Now second client no need to wait for first client to close by finishing its task.
//This server now handles 5 clients simultaneously. i.e. Now up to 5 clients simultaneously can send and receive messages from this server.
//Here concurrency is achieved  by creating a new child process which process e each new client while parent continues to accepting new connections.
#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define MAXSZ 100
int main()
{
int sockfd;//to create socket
int newsockfd;//to accept connection

struct sockaddr_in serverAddress;//server receive on this address
struct sockaddr_in clientAddress;//server sends to client on this address

int n;
char msg[MAXSZ];
int clientAddressLength;
int pid;

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=htonl(INADDR_ANY);
serverAddress.sin_port=htons(PORT);

//bind the socket with the server address and port
bind(sockfd,(struct sockaddr *)&serverAddress, sizeof(serverAddress));

//listen for connection from client
listen(sockfd,5);

while(1)
{
//parent process waiting to accept a new connection
printf("\n*****server waiting for new client connection:*****\n");
clientAddressLength=sizeof(clientAddress);
newsockfd=accept(sockfd,(struct sockaddr*)&clientAddress,&clientAddressLength);
printf("connected to client: %s\n",inet_ntoa(clientAddress.sin_addr));

//child process is created for serving each new clients
pid=fork();
if(pid==0)//child process rec and send
{
//rceive from client
while(1)
{
n=recv(newsockfd,msg,MAXSZ,0);
if(n==0)
{
close(newsockfd);
break;
}
msg[n]=0;
send(newsockfd,msg,n,0);

printf("Receive and set:%s\n",msg);
}//close interior while
exit(0);
}
else
{
close(newsockfd);//sock is closed BY PARENT
}
}//close exterior while

return 0;
}
/*
*****server waiting for new client connection:*****
connected to client: 127.0.0.1

*****server waiting for new client connection:*****
Receive and set:India

Receive and set:is

Receive and set:Great

connected to client: 127.0.0.1

*****server waiting for new client connection:*****
Receive and set:The

Receive and set:USA
 */

/************Client Code***********/
//CLIENT ITERATIVE

#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define SERVER_IP "127.0.0.1"
#define MAXSZ 100
int main()
{
int sockfd;//to create socket

struct sockaddr_in serverAddress;//client will connect on this

int n;
char msg1[MAXSZ];
char msg2[MAXSZ];

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=inet_addr(SERVER_IP);
serverAddress.sin_port=htons(PORT);

//client  connect to server on port
connect(sockfd,(struct sockaddr *)&serverAddress,sizeof(serverAddress));
//send to sever and receive from server
while(1)
{
printf("\nEnter message to send to server:\n");
fgets(msg1,MAXSZ,stdin);
if(msg1[0]=='#')
break;

n=strlen(msg1)+1;
send(sockfd,msg1,n,0);

n=recv(sockfd,msg2,MAXSZ,0);

printf("Receive message from  server::%s\n",msg2);
}

return 0;
}
/*
client:

ms@ubuntu:~/ipc_socket$ gcc tcpclient.c -o c
ms@ubuntu:~/ipc_socket$ ./c

Enter message to send to server:
India
Receive message from  server::India


Enter message to send to server:
IS
Receive message from  server::IS


Enter message to send to server:
Great
Receive message from  server::Great


Enter message to send to server:
*/

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network


C Linux Code for multi threaded socket client/Server file sharing ftp

Iterative TCP echo Server Code in C in Linux Platform

//TCP SERVER Iterative: only one client is handled
//if next client sends any thing the server will not receive till first client is not closed.
#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define MAXSZ 100
int main()
{
int sockfd;//to create socket
int newsockfd;//to accept connection

struct sockaddr_in serverAddress;//server receive on this address
struct sockaddr_in clientAddress;//server sends to client on this address

int n;
char msg[MAXSZ];
int clientAddressLength;

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=htonl(INADDR_ANY);
serverAddress.sin_port=htons(PORT);

//bind the socket with the server address and port
bind(sockfd,(struct sockaddr *)&serverAddress, sizeof(serverAddress));

//listen for connection from client
listen(sockfd,5);

//accept a connection
while(1)
{
printf("\n*****server waiting for new client connection:*****\n");
clientAddressLength=sizeof(clientAddress);
newsockfd=accept(sockfd,(struct sockaddr*)&clientAddress,&clientAddressLength);

//rceive from client
while(1)
{
n=recv(newsockfd,msg,MAXSZ,0);
if(n==0)
{
close(newsockfd);
break;
}
msg[n]=0;
send(newsockfd,msg,n,0);

printf("Receive and set:%s\n",msg);
}//close interior while
}//close exterior while

return 0;
}
/*
   ms@ubuntu:~/ipc_socket$ gcc tcpserver.c -o s
   ms@ubuntu:~/ipc_socket$ ./s

 *****server waiting for new client connection:*****
 Receive and set:India

 Receive and set:IS

 Receive and set:Great

 */

/**********Client*************/
//CLIENT ITERATIVE

#include<stdio.h>
#include<sys/types.h>//socket
#include<sys/socket.h>//socket
#include<string.h>//memset
#include<stdlib.h>//sizeof
#include<netinet/in.h>//INADDR_ANY

#define PORT 8000
#define SERVER_IP "127.0.0.1"
#define MAXSZ 100
int main()
{
int sockfd;//to create socket

struct sockaddr_in serverAddress;//client will connect on this

int n;
char msg1[MAXSZ];
char msg2[MAXSZ];

//create socket
sockfd=socket(AF_INET,SOCK_STREAM,0);
//initialize the socket addresses
memset(&serverAddress,0,sizeof(serverAddress));
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=inet_addr(SERVER_IP);
serverAddress.sin_port=htons(PORT);

//client  connect to server on port
connect(sockfd,(struct sockaddr *)&serverAddress,sizeof(serverAddress));
//send to sever and receive from server
while(1)
{
printf("\nEnter message to send to server:\n");
fgets(msg1,MAXSZ,stdin);
if(msg1[0]=='#')
break;

n=strlen(msg1)+1;
send(sockfd,msg1,n,0);

n=recv(sockfd,msg2,MAXSZ,0);

printf("Receive message from  server::%s\n",msg2);
}

return 0;
}
/*
client:

ms@ubuntu:~/ipc_socket$ gcc tcpclient.c -o c
ms@ubuntu:~/ipc_socket$ ./c

Enter message to send to server:
India
Receive message from  server::India


Enter message to send to server:
IS
Receive message from  server::IS


Enter message to send to server:
Great
Receive message from  server::Great


Enter message to send to server:
*/

Threaded Concurrent echo TCP Server Code in C in Linux Platform

Concurrent Server handling Multiple Clients Code in C in Linux Platform using fork.

Iterative TCP echo Server Code in C in Linux Platform

How data packets travel source to destination over the network


C Linux Code for multi threaded socket client/Server file sharing ftp

How data packets travel source to destination over the network

Understanding How Data Packets Travel Across the Network When troubleshooting IP networks over Ethernet it helps to understand how packets travel across the network.

Packets use two different mechanisms to get from point A to Point B, or from the source to the destination. IP addresses and MAC addresses.

The MAC address is the layer 2 address that represents the specific hardware that is connected to the wire. The IP address is the layer 3 address that represents the logical identity of the device on the network.

MAC Address Most every computer today has some sort of network interface card (NIC) either built-in or installed on the computer.
Every NIC is created with a hardware number permanently "burned" into it.

This permanent hardware number is known as the MAC (Media Access Control). MAC addresses are 48 bits in length and are usually displayed as a 12 digit hexadecimal number.
MM:MM:MM:HH:HH:HH
The first 24 bits (or 6 digits) represent the manufacturer of the NIC. The last 24 bits (6 digits) are a unique identifier that represents the Host or the card itself. No two MAC identifiers are alike.IP Address The IP address is the logical address that is associated with the MAC for a particular device. IP addresses (IPv4) are a 32 bit (12 digit) number representing 4 binary octets.Both an IP and a MAC are needed for data to travel across an Ethernet network.

The ARP Protocol When a computer sends data over the network, it first needs to find which route it must take. Will the packet stay on the network or does it need to leave the network. The computer first determines this by comparing the subnet mask to the destination ip address.

Once this destination is known, Address Resolution Protocol (ARP) is used to find the next hop on the network. ARP's job is to basically discover andassociate IP addresses to the physical MAC.
For a packet that has a destination on another network, ARP is used to find the MAC of the gateway router. An ARP packet is sent to the gateway router asking for it's MAC. The router reply's back to the computer with it's mac address. The computer will then forward the packet directly to the mac address of the gateway router.

When the gateway router receives the packet it will remove it's mac address as the destination and replace it with
the mac address of the next hop router. It will also replace the source computer's mac address with it's own mac address. This happens at each route along the way until the packet reaches it's destination.

Library Header rpm yum apt-get package managers in Linux

To use an applicaton/sw we need binary/executable/program in linux machine.
These binaries can be installed for use in Unix by:
1)directlt installing the binaries from
a)"apt-get install" package manager for debiana and debian like Linux
like Ubuntu.
b)"rpm -i "(yum, wrapper around rpm) for redhat, fadora and CentOS.
These package managers contains the repository urls for the softwares
for the current version of the OS.
2)by downloading the compress source code(.tg etc)
uncompress/tar and
cd ./config
make
make install.
--------
apt-advance packet Tool
rpm-red hat package manager
------
package in Linux first searched in local repositore ie /etc/yum.repos.d/
this contains link of server/repository for softwares to get
downloaded from and installed.
or
we can give the url of repository our self in /etc/yum.config file.
------
packages should be updates as might have new version of software have
been uploaded in the

repository or might be new security updates have come in the repository.
----------------
header files:
contains the declarations of the functions used in different modules
of a sw/application.
library:
implementation of the functions are given in .c/cpp files and compiled
into object

files(machine language/assembly language) and bundled into a single
file as library.
So, In future when any change is there in any function/sw then only
the respective
library is shared with the client using the sw or updated to Linux
Repository from where
Linux users can update their OS by
sudo ap-get update package-name