I am a complete newbie to networking, however I am a c/c++ programmer, and am working in objective-c (This is for OSX/iPhone).
I am trying to learn how to send a mag
This is my first working bit of code for two whole nights! Hopefully will help someone else! Thought I should share it, might save someone a bit of hassle.
I disabled the listen call, as I only wanted to send data.
+ (void)broadCast
{
int socketSD = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (socketSD <= 0) {
NSLog(@"Error: Could not open socket.");
return;
}
// set socket options enable broadcast
int broadcastEnable = 1;
int ret = setsockopt(socketSD, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
if (ret) {
NSLog(@"Error: Could not open set socket to broadcast mode");
close(socketSD);
return;
}
// Configure the port and ip we want to send to
struct sockaddr_in broadcastAddr;
memset(&broadcastAddr, 0, sizeof(broadcastAddr));
broadcastAddr.sin_family = AF_INET;
inet_pton(AF_INET, "255.255.255.255", &broadcastAddr.sin_addr);
broadcastAddr.sin_port = htons(33333);
char *request = "message from ios by c";
ret = sendto(socketSD, request, strlen(request), 0, (struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr));
if (ret < 0) {
NSLog(@"Error: Could not open send broadcast.");
close(socketSD);
return;
}
close(socketSD);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//[self listenForPackets];
});
}