I set up a simple client and server program using TCP socket to communicate. The server waits for the client to connect and reply whether it receives the message from the client. Below is how the code is implemented in the server and the client:
Code on the server-side:
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0)
error("ERROR writing to socket");
Code on the client-side:
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
else
printf("sucess. n = %d", n);
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
Now, assume that I starts the server and then starts the client, the client successfully connects to the server. Then I shuts down the server and tries to send a message from the client, the write()
operation returns no error. What I expect here is an error because the server actually does not receive any packets (it is shut down).
So my question is: is there any way to know whether the write()
(or send()
, sendto()
or sendmsg()
) successfully delivers the message to the server?