0

我正在尝试通过 UDP 套接字接收文本文件,客户端构建良好但提供了一个空白控制台,经过一些实验后我发现问题出在接收上,所以我发布了我的代码的那部分:

size_t data=0;
if(data=recvfrom( sd, file_buffer, sizeof(file_buffer), 0
                , (struct sockaddr *) &server, &server_length) < 0)
{
  printf("Error receiving file.");
  exit(1);
}

if(data==sizeof(file_buffer))
{
  printf("Received Data:[%s]",file_buffer);
}
4

1 回答 1

3

You should re-write you if you forgot to add parenthesis ()

if( data=recvfrom(sd, file_buffer, sizeof(file_buffer), 0, (struct sockaddr *) &server, &server_length)<0 )

Reason:
Precedence of < is higher then = So in your if() first < performed then = and this cause assigns data either 0 when data read successfully and 1 when recvfrom() returns -1 on error.
look @ C Operator Precedence Table

You code is equipment to on successfully read :

if(data = 1 < 0)

and on recvfrom() fail its like:

if(data = -1 < 0) 

Mistake? Actually you forgot () parenthesis (or if you don't know you shold add.) like:

if( (data=recvfrom(sd, file_buffer, sizeof(file_buffer), 0, (struct sockaddr *) &server, &server_length)) <0 )

see I added () like:

if( (data = recvfrom() ) < 0) 
    ^                  ^  added in your code 

Edit:

Second error: "buffer is not \0 terminated"

The function recvfrom() if successful worked, returns the length, in bytes, of the message or datagram. And if an end-of-file condition is received or the connection is closed, 0 is returned.

the thing to be notice is it doesn't puts '\0' symbol to terminate buffer. and you are using '%s' to print file_buffer[]'s content which excepts null terminated string that also cause Undefined Behavior at run time (and you may get unusual symbols on console if not getting segmentation-fault).

You should always read less then one of sizeof(file_buffer) and put null \0 explicitly, if you wants to use your file buffer as string.

I can suggest you do like:

no_Of_bytes =recvfrom( 
                sd, 
                file_buffer, 
                sizeof(file_buffer) - 1, 
                0,
                (struct sockaddr *) &server, 
                &server_length
            );
file_buffer[no_Of_bytes] = '\0';

Now your file_buffer is null terminated you can use with %s, but be sure you are not making mistakes in other part of code.

于 2013-04-06T06:09:37.750 回答