Question: a what is a socket b In socket programming, what goes on in the underlying () protocol when socket() is invoked successfully in an application
a what is a socket
b In socket programming, what goes on in the underlying () protocol when socket() is invoked successfully in an application program such as TCPEchoServer.c ?
#include
#include
#include
#include
#include
#include
#include"TCPEchoServer.h"
#define MAXPENDING 5 /* Maximum outstanding connection requests */
#define MAXBUF 100 //100
//void DieWithError(char *errorMessage); /* Error handling function */
//void HandleTCPClient(int clntSocket); /* TCP client handling function */
int main(int argc, char *argv[])
{
int servSock; /* Socket descriptor for server */
int clntSock; /* Socket descriptor for client */
struct sockaddr_in echoServAddr; /* Local address */
struct sockaddr_in echoClntAddr; /* Client address */
unsigned short echoServPort; /* Server port */
unsigned int clntLen; /* Length of client address data structure */
char buf[MAXBUF];
if (argc != 2) /* Test for correct number of arguments */
{
fprintf(stderr, "Usage: %s
exit(1);
}
echoServPort = atoi(argv[1]); /* First arg: local port */
/* Create socket for incoming connections */
if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
/* Construct local address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
echoServAddr.sin_port = htons(echoServPort); /* Local port */
/* Bind to the local address */
if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
DieWithError("bind() failed");
/* Mark the socket so it will listen for incoming connections */
if (listen(servSock, MAXPENDING) < 0)
DieWithError("listen() failed");
for (;;) /* Run forever */
{
/* Set the size of the in-out parameter */
clntLen = sizeof(echoClntAddr);
/* Wait for a client to connect */
if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr,
&clntLen)) < 0)
DieWithError("accept() failed");
/* clntSock is connected to a client! */
printf("Handling client %s ", inet_ntoa(echoClntAddr.sin_addr));
int ret=recv(clntSock,buf,MAXBUF-1,MSG_DONTWAIT);
if(ret==0)
{
close(clntSock);
}
HandleTCPClient(clntSock);
}
/* NOT REACHED */
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
