1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h>
int main(int argc, char *argv[]) { char* group = "239.255.255.250"; int port = 1982;
const char* sendData = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1982\r\nMAN: \"ssdp:discover\"\r\nST: wifi_bulb"; const char* info = "I'm server\n";
int sockfd; if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("recvudp"); return 1; }
int optname = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *) &optname, sizeof(optname)) < 0) { perror("recvudp"); return 1; }
struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port);
if (bind(sockfd, (struct sockaddr*) &addr, sizeof(addr)) < 0) { perror("recvudp"); return 1; }
struct ip_mreq mreq; mreq.imr_multiaddr.s_addr = inet_addr(group); mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq)) < 0) { perror("recvudp"); return 1; }
while (1) { #define BUFSIZE 256 char buf[BUFSIZE]; int numbytes, addrlen = sizeof(addr); memset(buf, 0, sizeof(buf));
if ((numbytes = recvfrom(sockfd, buf, BUFSIZE-1 , 0, (struct sockaddr *)&addr, &addrlen)) == -1) { perror("recvudp"); return 1; }
if(strcmp(buf,sendData)==0) { printf("\n%s\nLEN:%d bytes from %s\n", buf, numbytes,inet_ntoa(addr.sin_addr)); sendto(sockfd, info, strlen(info), 0, (struct sockaddr*) &addr, sizeof(addr)); } else { printf("LEN:%d bytes\n%s",numbytes,buf); } } return 0; }
|