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.