问题
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