hawxgamer

multicast sendet

Oct 13th, 2014
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <arpa/inet.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <unistd.h>
  9. #define MAX_LEN 1024
  10.  
  11. int main(int argc, char *argv[])
  12. {
  13. int sock;
  14. char message_to_send[MAX_LEN];
  15. unsigned int send_len;
  16. char* multicast_ip;
  17. unsigned short multicast_port;
  18. unsigned char multicast_ttl=1;
  19. struct sockaddr_in multicast_addr;
  20. /*
  21. if (argc != 3)
  22. {
  23. fprintf(stderr, "Usage: %s Multicast_IP Multicast_Port\n", argv[0]);
  24. exit(1);
  25. }
  26. */
  27. multicast_ip = "224.5.6.7";//argv[1]; /* arg 1: multicast IP address */
  28. multicast_port = 5006;//atoi(argv[2]); /* arg 2: multicast port number */
  29.  
  30. /* create a socket */
  31. if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
  32. {
  33. perror("Socket creation failed");
  34. exit(1);
  35. }
  36.  
  37. /* set the TTL (time to live/hop count) for the send */
  38. if ((setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (void*) &multicast_ttl, sizeof(multicast_ttl))) < 0)
  39. {
  40. perror("setsockopt() failed");
  41. exit(1);
  42. }
  43.  
  44. memset(&multicast_addr, 0, sizeof(multicast_addr));
  45. multicast_addr.sin_family = AF_INET;
  46. multicast_addr.sin_addr.s_addr = inet_addr(multicast_ip);
  47. multicast_addr.sin_port = htons(multicast_port);
  48.  
  49. printf("Type the message below (Press Enter to send, ctrl-C to quit):\n");
  50.  
  51. memset(message_to_send, 0, sizeof(message_to_send));
  52.  
  53. while (fgets(message_to_send, MAX_LEN, stdin))
  54. {
  55. send_len = strlen(message_to_send);
  56.  
  57. if ((sendto(sock, message_to_send, send_len, 0,
  58. (struct sockaddr *) &multicast_addr,
  59. sizeof(multicast_addr))) != send_len)
  60. {
  61. perror("Error in number of bytes");
  62. exit(1);
  63. }
  64.  
  65. memset(message_to_send, 0, sizeof(message_to_send));
  66. }
  67.  
  68. close(sock);
  69.  
  70. exit(0);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment