CFSocketSendData won't send Data?
I am a newbie to objective C networking. I have put together the code below for a simple WOL application. I can successfully create a socket, and then set an address (I only am able to set the local machine address but thats another question). However when trying to send the data using CFSocketSendData, it does not send the data(Data not sent message displayed). Am I using CFSocketSendData correctly, or is there a problem elsewhere?
Any help will be greatly appreciated, thanks.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT); //port
inet_aton(IP, &addr.sin_addr);//IP is the network IP of the machine e.g 192.168.0.2
NSData *address = [NSData dataWithBytes: &addr length: sizeof(addr)];
if (CFSocketSetAddress开发者_开发问答(WOLsocket, (CFDataRef)address) != kCFSocketSuccess){
NSLog(@"Address could not be set!");
}
else{
NSLog(@"Address set");
char ethadd []= "helloworld";
CFDataRef Data = CFDataCreate(NULL, (const UInt8*)ethadd, sizeof(ethadd));
if (CFSocketSendData(WOLsocket, NULL, Data, 0) < 0){
NSLog(@"Data could not be sent!");
}
else NSLog(@"Data Sent");
}
You didn't include the CFSocketCreate(...)
code in your snippet, but I assume that you chose the defaults, the PF_INET family and the TCP protocol.
With the TCP protocol, setting the address is not enough, you need to establish a connection to your destination endpoint.
First call the function...
CFSocketConnectToAddress (WOLsocket, address, 10.0);
then send your data...
CFSocketSendData(WOLsocket, NULL, Data, 0)
精彩评论