Braodcasting UDP Sockets in C using win32 API

痞子三分冷 提交于 2019-12-25 06:34:13

问题


I have created a Client Server Application using UDP Sockets. The Application works fine as there is only one server and one client. but now I want to make my Server "BROADCAST". How can I do it?| I had been trying to do it but it gives error at BIND function and returns an error "10049". here is my code snippet:

  #define broadcastPort  8888 

   WSADATA wsa;
   SOCKET s;
   //Initialise winsock
   printf("\nInitialising Winsock...");
   if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
   {
     printf("Failed. Error Code : %d",WSAGetLastError());
       exit(EXIT_FAILURE);
   }
   printf("Socket Initialised.\n");

   //Create a socket
   if((s = socket(AF_INET , SOCK_DGRAM , IPPROTO_UDP )) == INVALID_SOCKET)
   {
       printf("Could not create socket : %d" , WSAGetLastError());
   }
   printf("Socket created.\n"); 

   struct sockaddr_in serverSocket;
   char *broadcastPermission = "TRUE";
   if ((setsockopt(s, SOL_SOCKET, SO_BROADCAST,(char *)broadcastPermission,sizeof(broadcastPermission))) < 0){
       printf("%d",WSAGetLastError());
       while(1);
       //exit(1);
   } 

   ///Prepare the sockaddr_in structure///
   serverSocket.sin_family = AF_INET;
   serverSocket.sin_addr.s_addr = INADDR_BROADCAST;
   serverSocket.sin_port = htons( broadcastPort);

    //Bind
    if( bind(s ,(struct sockaddr *)&serverSocket , sizeof(serverSocket)) == SOCKET_ERROR)
    {
        printf("\nBind failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    printf("Bind done\n\n");

来源:https://stackoverflow.com/questions/15332023/braodcasting-udp-sockets-in-c-using-win32-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!