CFSocketContext socketContext = {0, self, NULL, NULL, NULL};
/* Create the server socket as a UDP IPv4 socket and set a callback */
/* for calls to the socket's lower-level accept() function */
cfSocket = CFSocketCreate(NULL, PF_INET, SOCK_DGRAM, IPPROTO_UDP, kCFSocketNoCallBack , NULL, &socketContext);
// getsockopt will return existing socket option value via this variable
int existingValue = 1;
// Make sure that same listening socket address gets reused after every connection
setsockopt( CFSocketGetNative(cfSocket),SOL_SOCKET, SO_REUSEADDR, (void *)&existingValue,sizeof(existingValue));
/* Set the port and address we want to listen on */
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(8081);
addr.sin_addr.s_addr = inet_addr([serverIP UTF8String]);
CFDataRef address = CFDataCreate(
kCFAllocatorDefault,
(UInt8*)&addr,
sizeof(addr));
char ethadd []= "0x0";
CFDataRef data = CFDataCreate(NULL, (const UInt8*)ethadd, sizeof(ethadd));
arguArray = [[NSMutableArray alloc]initWithObjects:(id)address, data,nil];
cfSource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, cfSocket, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), cfSource, kCFRunLoopDefaultMode);
//set the socket to no block mode before connecting with server
int flags = fcntl(CFSocketGetNative(cfSocket), F_GETFL,0);
fcntl(CFSocketGetNative(cfSocket), F_SETFL,flags|O_NONBLOCK);
NSLog(@"---flags----%d", flags);
send package
CFSocketSendData(cfSocket, (CFDataRef)[arguArray objectAtIndex:0], (CFDataRef)[arguArray objectAtIndex:1], 0);
recvfrom(CFSocketGetNative(cfSocket), (void *)&msg, MAX_UDP_DATAGRAM_SIZE, 0, (struct sockaddr *)&from_addr, &addr_len);