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

Find and grep for searching in directories and sub directories recurssively

Find Files Using
Name/permission/modifiedtime/type in
Current Directory/internal direcory
from current directory or from a
specific directory.
Try these combinations to get all the
answers.

[user02@localhost mnz14]$ find -name *.cpp
./gdb_2014_cs/w.cpp
./ds/queueLinkedList.cpp
./ds/zerotoendofarray.cpp
./ds/queueArray.cpp

[user02@localhost mnz14]$ find -name
*que*.cpp
./ds/queueLinkedList.cpp
./ds/queueArray.cpp


[user02@localhost mnz14]$ grep -r *.cpp
[user02@localhost mnz14]$ grep -r *.cpp *
[user02@localhost mnz14]$ grep -r "iostream"

[user02@localhost mnz14]$ grep -r "iostream" *.cpp
grep: *.cpp: No such file or directory

[user02@localhost mnz14]$ grep -r "iostream" *
ds/queueLinkedList.cpp:#include<iostream>
ds/zerotoendofarray.cpp:#include<iostream>
ds/queueArray.cpp:#include<iostream>
gdb_2014_cs/w.cpp:#include<iostream>
-------------------

1. Find Files Using Name in Current Directory

Find all the files whose name is tecmint.txt in a current working directory.
# find . -name tecmint.txt
./tecmint.txt

2. Find Files Under Home Directory

Find all the files under /home directory with name tecmint.txt.

# find /home -name tecmint.txt
/home/tecmint.txt

3. Find Files Using Name and Ignoring Case

Find all the files whose name is tecmint.txt and contains both capital
and small letters in /home directory.

# find /home -iname tecmint.txt

./tecmint.txt

./Tecmint.txt

4. Find Directories Using Name

Find all directories whose name is Tecmint in / directory.

# find / -type d -name Tecmint

/Tecmint

5. Find PHP Files Using Name

Find all php files whose name is tecmint.php in a current working directory.

# find . -type f -name tecmint.php



./tecmint.php

6. Find all PHP Files in Directory

Find all php files in a directory.

# find . -type f -name "*.php"

./tecmint.php

./login.php

./index.php

Part II - Find Files Based on their Permissions

7. Find Files With 777 Permissions

Find all the files whose permissions are 777.

# find . -type f -perm 0777 -print

8. Find Files Without 777 Permissions

Find all the files without permission 777.

# find / -type f ! -perm 777

9. Find SGID Files with 644 Permissions

Find all the SGID bit files whose permissions set to 644.

# find / -perm 2644

10. Find Sticky Bit Files with 551 Permissions

Find all the Sticky Bit set files whose permission are 551.

# find / -perm 1551

11. Find SUID Files

Find all SUID set files.

# find / -perm /u=s

12. Find SGID Files

Find all SGID set files.

# find / -perm /g+s

13. Find Read Only Files

Find all Read Only files.

# find / -perm /u=r

14. Find Executable Files

Find all Executable files.

# find / -perm /a=x

15. Find Files with 777 Permissions and Chmod to 644

Find all 777 permission files and use chmod command to set permissions to 644.

# find / -type f -perm 0777 -print -exec chmod 644 {} \;

16. Find Directories with 777 Permissions and Chmod to 755

Find all 777 permission directories and use chmod command to set
permissions to 755.

# find / -type d -perm 777 -print -exec chmod 755 {} \;

17. Find and remove single File

To find a single file called tecmint.txt and remove it.

# find . -type f -name "tecmint.txt" -exec rm -f {} \;

18. Find and remove Multiple File

To find and remove multiple files such as .mp3 or .txt, then use.

# find . -type f -name "*.txt" -exec rm -f {} \;

OR

# find . -type f -name "*.mp3" -exec rm -f {} \;

19. Find all Empty Files

To file all empty files under certain path.

# find /tmp -type f -empty

20. Find all Empty Directories

To file all empty directories under certain path.

# find /tmp -type d -empty

21. File all Hidden Files

To find all hidden files, use below command.

# find /tmp -type f -name ".*"

Part III - Search Files Based On Owners and Groups

22. Find Single File Based on User

To find all or single file called tecmint.txt under / root directory
of owner root.

# find / -user root -name tecmint.txt

23. Find all Files Based on User

To find all files that belongs to user Tecmint under /home directory.

# find /home -user tecmint

24. Find all Files Based on Group

To find all files that belongs to group Developer under /home directory.

# find /home -group developer

25. Find Particular Files of User

To find all .txt files of user Tecmint under /home directory.

# find /home -user tecmint -iname "*.txt"

Part IV - Find Files and Directories Based on Date and Time

26. Find Last 50 Days Modified Files

To find all the files which are modified 50 days back.

# find / -mtime 50

27. Find Last 50 Days Accessed Files

To find all the files which are accessed 50 days back.

# find / -atime 50

28. Find Last 50-100 Days Modified Files

To find all the files which are modified more than 50 days back and
less than 100 days.

# find / -mtime +50 -mtime -100

29. Find Changed Files in Last 1 Hour

To find all the files which are changed in last 1 hour.

# find / -cmin -60

30. Find Modified Files in Last 1 Hour

To find all the files which are modified in last 1 hour.

# find / -mmin -60

31. Find Accessed Files in Last 1 Hour

To find all the files which are accessed in last 1 hour.

# find / -amin -60

Part V - Find Files and Directories Based on Size

32. Find 50MB Files

To find all 50MB files, use.

# find / -size 50M

33. Find Size between 50MB - 100MB

To find all the files which are greater than 50MB and less than 100MB.

# find / -size +50M -size -100M

34. Find and Delete 100MB Files

To find all 100MB files and delete them using one single command.

# find / -size +100M -exec rm -rf {} \;

35. Find Specific Files and Delete

Find all .mp3 files with more than 10MB and delete them using one
single command.

# find / -type f -name *.mp3 -size +10M -exec rm {} \;

---------------

Search a string Recursively in all Directories

If you would like to search for a string in the current directory
along with all of the subdirectories, you can specify the -r option to
search recursively:

#grep -r "main" *

#grep -r main *

1. Search and Find Files

Let's say that you have just installed a fresh copy of the new Ubuntu
on your machine, and that you are going to give Python scripting a
shot. You have been scouring the web looking for tutorials, but you
see that there are two different versions of Python in use, and you
don't know which one was installed on your system by the Ubuntu
installer, or if it installed any modules. Simply run this command:

# dpkg -l | grep -i python

Sample Output

ii python2.7 2.7.3-0ubuntu3.4
Interactive high-level object-oriented language (version 2.7)

ii python2.7-minimal 2.7.3-0ubuntu3.4
Minimal subset of the Python language (version 2.7)

ii python-openssl 0.12-1ubuntu2.1
Python wrapper around the OpenSSL library

ii python-pam 0.4.2-12.2ubuntu4
A Python interface to the PAM library

First, we ran dpkg -l, which lists installed *.deb packages on your
system. Second, we piped that output to grep -i python, which simple
states "go to grep and filter out and return everything with 'python'
in it." The -i option is there to ignore-case, as grep is
case-sensitive. Using the -i option is a good habit of getting into,
unless of course you are trying to nail down a more specific search.

2. Search and Filter Files

The grep can also be used to search and filter within individual files
or multiple files. Lets take this scenario:

You are having some trouble with your Apache Web Server, and you have
reached out to one of the many awesome forums on the net asking for
some help. The kind soul who replies to you has asked you to post the
contents of your /etc/apache2/sites-available/default-ssl file.
Wouldn't it be easier for you, the guy helping you, and everyone
reading it, if you could remove all of the commented lines? Well you
can! Just run this:

# grep -v "#" /etc/apache2/sites-available/default-ssl

The -v option tells grep to invert its output, meaning that instead of
printing matching lines, do the opposite and print all of the lines
that don't match the expression, in this case, the # commented lines.

3. Find all .mp3 Files Only

The grep can be very useful for filtering from stdout. For example,
let's say that you have an entire folder full of music files in a
bunch of different formats. You want to find all of the *.mp3 files
from the artist JayZ, but you don't want any of the remixed tracks.
Using a find command with a couple of grep pipes will do the trick:

# find . -name "*.mp3" | grep -i JayZ | grep -vi "remix"