title: Broadcast UDP message in LAN to detect IP cameras
body: <p>I am trying to build a small programm for my iPhone which allows to detect devices on my local network (especially IP cameras). I know that some of those support protocols like UPnP and I have been playing around with that as well, but I now want to implement the communication between my iPhone and the camera completely by myself without relying on a library.</p>
  
  <p>My approach is to send a broadcast message out to the local network and parse the responses that are received. For example, in order to detect UPnP devices on the local network, the message that is broadcasted needs to have the following content:</p>
  
  <pre><code>M-SEARCH * HTTP/1.1\r\nHOST:255.255.255.255:1900\r\nMAN:\"ssdp:discover\"\r\nST:ssdp:all\r\nMX:1\r\n\r\n
  </code></pre>
  
  <p>I am a bit familiar with network programming in C, so I want to write the code for the communication in C and integrate in my Objective-C later on. </p>
  
  <p>I am currently doing the following:</p>
  
  <pre><code>// Create socket
  int sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  
  // Enable broadcast messaging
  int broadcastEnable = 1;
  int ret = setsockopt(sd, SOL_SOCKET, SO_BROADCAST, &amp;broadcastEnable, sizeof(broadcastEnable));
  
  // Configure the port and ip we want to send to
  struct sockaddr_in broadcastAddr; // Make an endpoint
  memset(&amp;broadcastAddr, 0, sizeof broadcastAddr);
  broadcastAddr.sin_family = AF_INET;
  inet_pton(AF_INET, "255.255.255.255", &amp;broadcastAddr.sin_addr); // Set the broadcast IP address
  broadcastAddr.sin_port = htons(1900); // Set port 1900
  
  // Create the broadcast UPnP request
  char *request = "M-SEARCH * HTTP/1.1\r\nHOST:255.255.255.255:1900\r\nMAN:\"ssdp:discover\"\r\nST:ssdp:all\r\nMX:1\r\n\r\n";
  
  // start the broadcast
  success = sendto(sd, request, strlen(request), 0, (struct sockaddr*)&amp;broadcastAddr, sizeof broadcastAddr);
  </code></pre>
  
  <p>Now, I am stuck at this point, since I don't know how to process any answers. Will the replies from the UPnP devices come in on the same socket? I believe it should be able to receive the incoming replies with recv() of recvfrom() but I am not sure how exactly to implement them. Do I have to create a new socket or can I just the existing one? Does the socket have to be bound using bind()?</p>