GOAL: I’m making a UDP socket to send and receive data.
I am testing this on my laptop, so I have a server running on the background that listens to incoming messages and echoing this back.
PROBLEM: I am seeing that the server receives one string, and when it echoes back, the client reads the string 2 times instead of ONE and adds gibberish.How to solve this?
Output from the code is: HelloHello09[btw i als get some questionsmarks that are upside down in front of the 09 and behind it, but I cannot paste it, lolz]
Code:
#define BUFLEN 5
#define PORT 12345
#import <Foundation/Foundation.h>
#define srvr_IP "127.0.0.1"
void errorSig(char *);
int main (int argc, const char * argv[])
{
int sockSend = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in si_other;
char buf[BUFLEN] = "Hello";
char bufrec[BUFLEN];
@autoreleasepool {
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
inet_pton(AF_INET, srvr_IP, &si_other.sin_addr);
memset(&si_other.sin_zero, 0, sizeof(si_other.sin_zero));
int size = sizeof(si_other);
sendto(sockSend, buf, BUFLEN, 0,
(struct sockaddr *)&si_other, size);
recvfrom(sockSend, bufrec, BUFLEN, 0, (struct sockaddr *)&si_other, (unsigned int*)&size);
NSString *test = [[NSString alloc]initWithUTF8String:bufrec];
NSLog(@" data is: %@", test);
close(sockSend);
}
return 0;
}
I’ve just seen that you did in fact define BUFLEN as 5 (sorry I missed that when I wrote my comment above). As I suspected, you have a NULL termination issue. The length of a string in C is one more than the number of characters you want to store, to make room for the NULL terminator indicating the end of the string.
Change your BUFLEN definition to 6 and you should find it works much better.