2

I'm a beginner in socket programming in linux env.

the code is :

void proccess_server(int s)
{

    ssize_t size =0 ;
    char buffer[1024];
    for(;;)
    {
        printf("proccess:%d proccessing socket :%d\n",getpid(),s);
        size = recv(s,buffer,sizeof(buffer),0);

        if(0 == size)
          return ;
        sprintf(buffer,"Response from server:%d,%d bytes altogether\n",getpid(),size);

        send(s,buffer,strlen(buffer)+1,0);
    }

}

and I don't understand why len param in send() add another byte (strlen(buffer)+1) in send(s,buffer,strlen(buffer)+1,0);

please help me !

3
  • This code is all wrong, where did you find it ? It does not check for error conditions (size == -1), and it expect "buffer" to be null terminated without checking for it, so it has a security flaw. Commented Jan 1, 2012 at 11:12
  • er..It's a simple tutorial show the network programming api form my text book. and if I want to fix it ,should I fill buffer with \0 before receive data? Commented Jan 1, 2012 at 14:39
  • yes, and you should recv sizeof(buffer)-1 bytes at most. Commented Jan 1, 2012 at 17:06

1 Answer 1

2

In C language, compiler puts a \0 (NULL) character at the end of every string. So while you are using a string, computer can understand where that string ends. In Pascal language example, compiler puts a byte front of string to store length of string.

This must be the reason why there is +1 there.

Sign up to request clarification or add additional context in comments.

2 Comments

I see,I understand there will be a \0 at the end of the string,as the question is ,+1 means the function strlen() return the length of a string not include \0?
Yes, that is right. If a string is "abc", strlen("abc") is 3, but in memory length is 4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.