Writing an application which sends 4 ints over socket, trying the following but getting 0s at receiving end…
I assume this is something to do with the way I’m passing them signedness & endianness etc…
int _send(int sock, int c, int x, int y, int w)
{
int cc, xc, yc, wc;
char buf[16];
int offset;
struct sockaddr_in sap;
char echoBuffer[1]; /* Buffer for echo string */
int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv() and total bytes read */
offset = 0;
buf[offset] = htonl(c);
buf[4] = htonl(x);
buf[8] = htonl(y);
buf[12] = htonl(w);
if (send(sock, buf, 16, 0) != 16)
{
printf("send() sent a different number of bytes than expected");
return(-1);
}
//...
}
And this is the code at the receiving end:
while (listen(sock, 2) == 0)
{
printf("listened...\r\n");
int addrlen;
struct sockaddr_in address;
addrlen = sizeof(struct sockaddr_in);
int channel = accept(sock, (struct sockaddr *)&address, &addrlen);
if (channel<0)
{
perror("Accept connection");
return -1;
}
else {
printf("accepted\r\n");
while (1)
{
int size = 16;
char buffer[16];
recv( channel, buffer, size, 0);
for (int i=0; i<=12; i+=4)
{
int c = ntohl(buffer[i]);
printf("%d\r\n", c);
}
}
this is broken. you should declare array of
integers. Reason is thatbuf[i] = xmeants put a byte at i-th cell, and if it doesn’t fit then truncate. That is what is happening.