3

Does anyone know how the delegate method for receiving UDP data in CocoaAsyncSockets work when it comes to fetching the source address? Specifically the method

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext

The address comes back as NSData* but interpreting it using NSUTF8StringEncoding returns null and NSASCIIStringEncoding returns a bunch of garbled characters. How is it supposed to be interpreted?

Rick
  • 3,240
  • 2
  • 29
  • 53
  • Yeah, I want to accomplish is more or less the same. I did however find a more effective solution than the one posted there. – Rick Aug 01 '13 at 14:10
  • 1
    For IPv4 addresses that is fine. I posted the "more complicated" code there because it works also with IPv6, which is used more and more. – Martin R Aug 01 '13 at 14:14
  • Aha, gotcha. :) Thanks – Rick Aug 01 '13 at 14:50

1 Answers1

2

Figured out how to do it, the data is in the form of a struct sockaddr_in*. After importing <arpa/inet.h>you can do the following:

struct sockaddr_in *addr = (struct sockaddr_in *)[address bytes];
NSString *IP = [NSString stringWithCString:inet_ntoa(addr->sin_addr) encoding:NSASCIIStringEncoding];
Rick
  • 3,240
  • 2
  • 29
  • 53