I am having troubles receiving the string I am sending with a UDP packet when this string is dynamically created (when i set its value equal to the one of another variable in my code). This problem does not present itself when, differently, I set a constant value to the string when this one is created.
Here is the method i use for sending the string:
- (void) sendUDPMessage {
int sockfd;
struct sockaddr_in server_addr;
char myBroad[]="255.255.255.255";
struct hostent *hptr = gethostbyname(myBroad);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&server_addr, sizeof(struct in_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(15000);
server_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
memcpy(&server_addr.sin_addr, hptr->h_addr_list[0], sizeof(struct in_addr));
int opt = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(int));
NSString *string = [NSString stringWithFormat:@"%@ %@",user.name,user.surname];
sendto(sockfd, &string, sizeof(string), 0, (struct sockaddr*)&server_addr, sizeof server_addr);
NSLog(@"message sent : %@",string);
}
And this is the method for receiving the udp packet:
- (void) server {
int serverfd;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
serverfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&server_addr, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(15000);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(serverfd, (struct sockaddr *) &server_addr, sizeof(struct sockaddr_in));
socklen_t clisize = sizeof(struct sockaddr_in);
bzero(&client_addr, clisize);
while (1) {
NSString *string=@"";
NSLog(@"wainting for messages");
recvfrom(serverfd, &string, 200, 0, (struct sockaddr *) &sin, &clisize);
NSLog(@"message received : %@",string);
}
}
If I define NSString * string = @”hello!”; I can correctly receive the content of the string. The same problem is present when i try to send an NSObject.
What am I missing? Thanks!
If your goal is to use sockets for some actual purpose, you should give GCDAsyncSocket (and related classes) a try.
If this is just playing around to get some insight into how sockets work (and/or if you want to use this in C projects as well) here is a fixed version of your code:
And this is the method for receiving the udp packet:
(untested)
Various problems still exist in this code, this is only usable as a quick demo. E.g. that all return values should be checked, all errors should be handled, you should be aware that calls may block (unless you specifically prevent this), you should receive the entire message before creating to an
NSString(e.g. if the received packet is bigger than the buffer; you cannot do this in parts naively because UTF-8 has multibyte characters)You have been warned!