Socket B Socket Programming Goes Underlying Protocol Socket Invoked Successfully Applicati Q43843397
a what is a socket
b In socket programming, what goes on in the underlying (下层的)protocol when socket() is invoked successfully in an applicationprogram such as TCPEchoServer.c ?
#include <stdio.h> /*for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), bind(), andconnect() */
#include <arpa/inet.h> /* for sockaddr_in andinet_ntoa() */
#include <stdlib.h> /* foratoi() and exit() */
#include <string.h> /* formemset() */
#include <unistd.h> /* forclose() */
#include”TCPEchoServer.h”
#define MAXPENDING 5 /* Maximumoutstanding connection requests */
#define MAXBUF 100 //接受数据缓冲区最大字节数为100
//void DieWithError(char *errorMessage); /* Errorhandling function */
//void HandleTCPClient(int clntSocket); /* TCPclient handling function */
int main(int argc, char *argv[])
{
intservSock; /*Socket descriptor for server */
intclntSock; /*Socket descriptor for client */
struct sockaddr_in echoServAddr; /*Local address */
struct sockaddr_in echoClntAddr; /*Client address */
unsigned shortechoServPort; /* Server port */
unsigned intclntLen; /*Length of client address data structure */
char buf[MAXBUF];
if (argc !=2) /* Test for correct number ofarguments */
{
fprintf(stderr,”Usage: %s <Server Port>n”, argv[0]);
exit(1);
}
echoServPort =atoi(argv[1]); /* First arg: local port*/
/* Create socket for incomingconnections */
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); /* Localport */
/* Bind to the local address */
if (bind(servSock, (struct sockaddr *)&echoServAddr, sizeof(echoServAddr)) < 0)
DieWithError(“bind()failed”);
/* Mark the socket so it will listen forincoming connections */
if (listen(servSock, MAXPENDING) <0)
DieWithError(“listen()failed”);
for (;;) /* Run forever */
{
/* Set the sizeof the in-out parameter */
clntLen =sizeof(echoClntAddr);
/* Wait for aclient to connect */
if ((clntSock =accept(servSock, (struct sockaddr *) &echoClntAddr,
&clntLen))< 0)
DieWithError(“accept()failed”);
/* clntSock isconnected to a client! */
printf(“Handlingclient %sn”, inet_ntoa(echoClntAddr.sin_addr));
intret=recv(clntSock,buf,MAXBUF-1,MSG_DONTWAIT);
if(ret==0)
{
close(clntSock);
}
HandleTCPClient(clntSock);
}
/* NOT REACHED */
}
Expert Answer
Answer to a what is a socket b In socket programming, what goes on in the underlying (下层的) protocol when socket() is invoked…
OR