TCP CONNECTION ESTABLISHMENT


AIM:
           To write a program for TCP connection establishment.

ALGORITHM:
SERVER:

    STEP 1: Start
    STEP 2: Declare the variables for the socket
    STEP 3: Specify the family, protocol, IP address and port number
    STEP 4: Create a socket using socket() function
    STEP 5: Bind the IP address and Port number
    STEP 6: Listen and accept the client’s request for the connection
    STEP 7: Establish the connection with the client
    STEP 8: Close the socket
    STEP 9: Stop
CLIENT:
    STEP 1: Start
    STEP 2: Declare the variables for the socket
    STEP 3:  Specify the family, protocol, IP address and port number
    STEP 4: Create a socket using socket() function
    STEP 5: Call the connect() function
    STEP 6: Close the socket
    STEP 7: Stop

SOURCE CODE:
SERVER:

#include<stdio.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<sys/types.h>
#define SERV_TCP_PORT 5035
int main(int argc,char **argv)
{
       int sockfd,newsockfd,clength;
       struct sockaddr_in serv_addr,cli_addr;
       sockfd=socket(AF_INET,SOCK_STREAM,0);
       serv_addr.sin_family=AF_INET;
       serv_addr.sin_addr.s_addr=INADDR_ANY;
       serv_addr.sin_port=htons(SERV_TCP_PORT);
       printf("\nStart");
       bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
       printf("\nListening...");
       listen(sockfd,1);
       clength=sizeof(cli_addr);
       newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&clength);
       printf("\nAccepted\n");
       close(sockfd);
       return 0;
}
CLIENT:
#include<stdio.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<sys/types.h>
#define CLI_TCP_PORT 5035
int main(int argc,char **argv)
{
       int sockfd;
       struct sockaddr_in serv_addr;
       struct hostent * server;
       sockfd=socket(AF_INET,SOCK_STREAM,0);
       serv_addr.sin_family=AF_INET;
       serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
       serv_addr.sin_port=htons(CLI_TCP_PORT);
       printf("\nReady for connect\n");
       connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
       close(sockfd);
       return 0;
}

OUTPUT:
SERVER:















CLIENT:















RESULT:
    Thus the program for TCP connection establishment was executed and the output was verified.
Previous
Next Post »

Still not found what you are looking for? Try again here.