Skip to main content

brief description about linux socket programming


steps for client socket connection

1. create a client socket
2. connect with server
3 read and wirte data

steps for socket server connection

1.create a sockets system call
2.bind the socket to an address using the bind()
3.listen for connection with the listen system call
4.Accept the system call with Accept()
5.send and receive call using read and write

two socket can connect if there address domain and the socket type  are same and should b same domain.
there are two most used address domains one is unix domain and another is internet domain in which two processes runinf on any two hosts on the internet communicate.each of these has its own address format.
in unix Domain address of a socket in character string format which is basically an entry in the file system.
the address of a socket in internet domain consist of the internet address of the host machine (every computer on the internet has a unique 32 bit address ,often refered to a its IP address)
In addition ,each socket needs a port number on the host.
port number are 16 bit unsigned integers.
the lowers number are reserved in unix system for standard services.for example the port number for the ftp server is 21 .it is important that standard services be at the same port on all computer so the clients will know their addresses.
however port number above 2000 are generally available and max range is 65535.
there are two types of sockets type one is stream sockets and another datagram socket
stream socket is used for tcp and datagram is used for the UDP connection.
header files for socket is
#include <sys/socket.h>
#include <netinet/in.h>
this header file contain the constant and structer needed for internet domain addresses.
A sockaddr_in is a structure containing an internet address.this structure is defined in netinet/in.h
struct sockaddr_in
{
 short sin_family;/must be AF_INET
 u_short sin_port;
 struct in_addr sin_addr;
 char sin_zero[8];
};
an in_addr structure defined in the same header file ,contains only one field a unsigned long called s_addr;

defination of socket is a defined method of connecting two processes,locally or across network.it is an API used for communication for two interprocess.

int sockfd=socket(AF_INET,SOCK_STREAM,0);

socket third paramtere is a protocal by default use zero means operating system choose the most appropriate protocal.it will choose   TCP for stream sockets and udp for datagram.
bzero((char*)&serv_addr,sizreof(serv_addr));
bzero takes two arguments ,first is pointer to the buffer and second is sizeof the buffer.thus this initalizes serv_addr to zeros.

next is sockaddr_in stuct varaiable is serv_addr.
its first field is short sin_family is AF_INET.
serv_addr.sin_port=htons(portno).
htons converts the host to network byte order
serv_addr.sin_addr.s_addr=INADDR_ANY;
last field contains the host IP address.

after bind () will call for the bind the sockets with an address.
it takes three arguments first is
1.first is socket() file descriptor.
2.struct sockaddr_in
3. size of sockaddr_inb
for exam:-
bind(sockfd,(struct sockaddr*)serv_addr,sizeof(serv_addr))


next method is listen system call allow the process to listen on the socket for connections.the fitst argument is the socket file descriptor and the second is size of the backlod queue i.e. the number of connection that can be waiting while the process is handling a particualr connection.
listen(sockfd,5).
here we set to backlog queue 5 ,the maximum size is permitted by most systems.

next call is accept()system call causes the process to block untill a client connection to the server.thus it wakes up the process when a connection from a client has been successfully establish its return the new file derciptor.
newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&clilen);

accept takes the client struct as a second parameter and third parameter is as a sizeof of client address.


next proceess read and wirte system call
read(newsockfd,buffer,255);
write(newsockfd,"hi this is working",255);



next Client socket process:-
all header will be same one header file add is
#include <netdb.h>
this is used for hostent struct
struct hostent
{
 char *h_name;//offical name of host
 char **h_aliases ;//alias list
 int  h_addrtype;//host address type
 int  h_length;//length of address
 char **h_addr_list;/*list of address from one server */
 #define h_addr h_addr_list[0] /*address,for backward compatibility*/

};

struct hostent *gethostbyname(char * name)
it takes a name as an argument and return a pointer hostent conatining information about the host.
the field char *h_addr conatains the IP address.
if this struct is NULL ,the system could not locate a host with this name
bcopy((char *)server->h_addr,
      (char *)&serv_addr.sin_addr.s_addr,
      server->h_length);
serv_addr.sin_port = htons(portno);)

if(connect (sockfd),&serv_addr,sizeof(serv_Addr)serv_addr.sin_family = AF_INET;
after successfully connect it read and write process start;
fgets(buffer,255,stdin)
int n=write(sockfd,buffer,strlen(buffer));



to allow multiple connection simultaneous connection,we make the following changes to the code:
1. put the accept statement and the followind code in the infinite loop
2.after a connection is establish call fork() to create a new process.
3 child process will close sockfd and call #dostuff passing the new socket file descriptor as an argument.when the two process have completed their conversation as indicated by dostuff() returning this simply exits
4.The parent process closes newsockfd####. Because all of this code is in an infinite loop, it will return to the accept statement to wait for the next connection.


while (1)
 {
   newsockfd = accept(sockfd,
               (struct sockaddr *) &cli_addr, &clilen);
   if (newsockfd < 0)
     error("ERROR on accept");
   pid = fork();
   if (pid < 0)
     error("ERROR on fork");
   if (pid == 0)
   {
     close(sockfd);
     dostuff(newsockfd);
     exit(0);
   }
   else
     close(newsockfd);
 }

Comments

Popular posts from this blog

Microservice Architecture

Agile development & Deployment is difficult in case of ____ Monolithic Software built as microservices can, by definition, be broken down into multiple component services ? True Separating components with conflicting resource requirements falls under the bucket of _ Microservices Complexity of developing, testing & deploying distributed system, Handling partial failures account to disadvantages of Microservices Benefits of Microservices include - All the options Decomposition of Microservices based on 2 categories namely Business capability , Subdomain Simple to Develop, Test, Deploy, Scale represents ____ Monolithic Is Microservice is considered as subset of SOA ? True The 3Cs of Microservices includes all these except Control Microservice Architecture adapts following concepts All the options The client expects a timely response from the service and might even block while it waits represents__client service interaction styles Synch...

What is Document/View Architecture in MFC?

By default MFC application wizard creats with an skeleton with a document class and another is view class.MFC seperates data management into these two class.The document class store the data and print the data and view display the data and manages the user interaction with it. Notepad is simple example for SDI application. or ALL MFC application which have user interface follow this architecture. Any MFC application creates with two basic skeleton one is document class and another is view class.document manages the data for multiple view,and view class displays the data. MFC document/view architecture makes it easy to support multiple view,multiple document types, splitter windows and other valuable user interface features. . For exm:- in SDI application we have following major class:- 1. CMainFrameApp:- Frame class derived  from the CFrameWnd 2. CMySDIView :- View class derived  from the CView class 3. CMainDoc :- Document class derived  from the CDoc...