Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4015706
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T09:39:06+00:00 2026-05-20T09:39:06+00:00

I wrote some code in C for a TCP Server that echoes whatever it

  • 0

I wrote some code in C for a TCP Server that echoes whatever it gets. The problem is when I send data first time it echoes it and next times the server sends back the first packet I sent. The log looks like:

Client Send : Packet1
Server reply : Packet1
Client Send : Packet2
server reply : Packet1

The server code is as follows:

int main(int argc, char** argv) {
int listenfd,connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in servaddr,cliaddr;
listenfd = socket(AF_INET,SOCK_STREAM,0);
printf("Socket listenfd : %d    with %d And %d\n",listenfd,AF_INET,SOCK_STREAM);
bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
printf("Server address: %d\n",servaddr.sin_addr.s_addr);
bind(listenfd, (SA*) &servaddr, sizeof(servaddr));
printf("Listened: %d\n",listenfd);
listen(listenfd,LISTENQ);
printf("After Listening: %d\n",listenfd);
int num=0;
for( ; ; ){
    clilen=sizeof(cliaddr);
    connfd = accept(listenfd, (SA*) &cliaddr,&clilen);
    printf("Client no. %d connected\n",++num);
    if( (childpid=fork())==0){
        close(listenfd);
        echo(connfd);
        exit(0);
    printf("Client no. %d Terminated\n",++num);
    }
   close(connfd);
}
return (EXIT_SUCCESS);
}

And my echo function:

void echo(int sockfd) {
 ssize_t n;
 char    buf[MAXLINE];
 again:
 while ( (n = read(sockfd, buf, MAXLINE)) > 0)
     writen(sockfd, buf, n);
if (n < 0 && errno == EINTR)
     goto again;
 else if (n < 0)
     printf("read error");
}

the client code main :

int main(int argc, char** argv) {
int sockfd;
struct sockaddr_in servaddr;

sockfd= socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));

servaddr.sin_family = AF_INET;
servaddr.sin_port= htons(SERV_PORT);
inet_pton(AF_INET,"0.0.0.0",&servaddr.sin_addr);
printf("%d , %d \n",sockfd,servaddr.sin_addr.s_addr);
connect(sockfd, (SA*) &servaddr,sizeof(servaddr));
printf("%d\n",sockfd);
replyBack(stdin,sockfd);

printf("RETURN\n");
return (EXIT_SUCCESS);
}

the replyBack function:

void replyBack(FILE *fp, int sockfd) {
char sendline[MAXLINE], recvline[MAXLINE];
printf("ENTER  YOUR ECHOED:  \n");
while (fgets(sendline, MAXLINE, stdin) != NULL) {
    write(sockfd, sendline, sizeof(sendline));

    if (read(sockfd, recvline, MAXLINE) == 0)
    {
        printf("str_cli: server terminated prematurely");
        exit(-1);
    }
    fputs(recvline, stdout);

}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T09:39:07+00:00Added an answer on May 20, 2026 at 9:39 am

    Well, let’s look at this section of your code:

    printf("After Listening: %d\n",listenfd);
    int num=0;
    for( ; ; ){
        clilen=sizeof(cliaddr);
        connfd = accept(listenfd, (SA*) &cliaddr,&clilen);
        printf("Client no. %d connected\n",++num);
        if( (childpid=fork())==0){
            close(listenfd);
            echo(connfd);
            exit(0);
        printf("Client no. %d Terminated\n",++num);
        }
       close(connfd);
    }
    

    Calling exit exits your application, so the printf following it will never get executed. Minor, but worth pointing out.

    Also, in the “child” process, you should not close your listening socket. The only socket it should work with is the client connection, so you should have something more along the lines of:

    if ( (childpid = fork ()) == 0 ) {
      echo ( connfd );
      close ( connfd );
      printf ( "Client no %d terminated.\n", num ); /* Don't use the ++ here or your count will be off */
      exit ( 0 );
    }
    

    Now let’s look at your echo code:

    void echo(int sockfd) {
      ssize_t n;
      char    buf[MAXLINE];
      again:
      while ( (n = read(sockfd, buf, MAXLINE)) > 0)
          writen(sockfd, buf, n);
     if (n < 0 && errno == EINTR)
          goto again;
     else if (n < 0)
          printf("read error");
    }
    

    Have to remember that the calls to read and write may block (since I don’t see you setting the socket to non-blocking IO), and write may not send the entire buffer when called, so you need to check a few more things here.

    void
    echo ( int sockfd )
    {
      ssize_t bytes_in, bytes_out, bytes_remaining;
      int write_err;
      char buf[MAXLINE];
      char * send_start_pos;
      while ( 1 ) {
        bytes_in = read ( sockfd, buf, MAXLINE );
        if ( bytes_in < 1 ) {
          if ( errno == EINTR )
            continue;
          break; /* other error occurred, or EOF (0 bytes read) */
        }
        bytes_remaining = bytes_in;
        send_start_pos = buf;
        write_err = 0;
        while ( ( bytes_remaining > 0 ) && !( write_err ) ) {
          bytes_out = write ( sockfd, send_start_pos, bytes_remaining );
          if ( bytes_out < 0 ) {
            if ( errno == EINTR )
              continue;
            write_err = 1;
            break;
          }
          bytes_remaining -= bytes_out;
          send_start_pos += bytes_out;
        }
        if ( write_err )
          break;
      }
    }
    

    Once your echo function exits, the socket will be closed back in the calling function. Generally, I would suggest closing the socket in the echo function, unless you need it afterwards. I almost certainly would suggest closing it when an error occurs, but, again, that is up to you.

    Just as an aside, stay away from goto … it has its purposes, but for the most part, well-written code rarely ever uses it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wrote some code with a lot of recursion, that takes quite a bit
I recently wrote some javascript code that filled a drop down list based on
Some time ago I wrote a little piece of code to ask about on
I am testing some weird-looking CSS code that I wrote (I'm using a mix
I have some code that seems to not handle it well when a TCP
I wrote some CSS in my HTML code to create rollover buttons. Then i
I needed some simple string encryption, so I wrote the following code (with a
I was trying to write some code that would check if an item has
I'd like to write some unit tests for some code that connects to a
For our webservice, I wrote some logic to prevent multipart/form-data POSTs larger than, say,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.