Created
April 6, 2011 01:23
-
-
Save chrishulbert/904951 to your computer and use it in GitHub Desktop.
Send a broadcast udp message using c / obj-c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <netinet/in.h> | |
#include <sys/socket.h> | |
#include <unistd.h> | |
#include <arpa/inet.h> | |
- (void)sendBroadcastPacket { | |
// Open a socket | |
int sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); | |
if (sd<=0) { | |
NSLog(@"Error: Could not open socket"); | |
return; | |
} | |
// Set socket options | |
// Enable broadcast | |
int broadcastEnable=1; | |
int ret=setsockopt(sd, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable)); | |
if (ret) { | |
NSLog(@"Error: Could not open set socket to broadcast mode"); | |
close(sd); | |
return; | |
} | |
// Since we don't call bind() here, the system decides on the port for us, which is what we want. | |
// Configure the port and ip we want to send to | |
struct sockaddr_in broadcastAddr; // Make an endpoint | |
memset(&broadcastAddr, 0, sizeof broadcastAddr); | |
broadcastAddr.sin_family = AF_INET; | |
inet_pton(AF_INET, "239.255.255.250", &broadcastAddr.sin_addr); // Set the broadcast IP address | |
broadcastAddr.sin_port = htons(1900); // Set port 1900 | |
// Send the broadcast request, ie "Any upnp devices out there?" | |
char *request = "M-SEARCH * HTTP/1.1\r\nHOST:239.255.255.250:1900\r\nMAN:\"ssdp:discover\"\r\nST:ssdp:all\r\nMX:1\r\n\r\n"; | |
ret = sendto(sd, request, strlen(request), 0, (struct sockaddr*)&broadcastAddr, sizeof broadcastAddr); | |
if (ret<0) { | |
NSLog(@"Error: Could not open send broadcast"); | |
close(sd); | |
return; | |
} | |
// Get responses here using recvfrom if you want... | |
close(sd); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
REALLY SUPER. Need more in detail the other files i mean
.h,.m class files