Many people in these two days are asking how to use socket to realize broadcast (Boardcast)
Just I have done this program, here is the simple code to write a broadcast sent and accepted example:
//
// Transmitter program
#include
int main (int argc, char * argv []) {WSADATA wsaData; // pointer to the information structure SOCKET sockListener WinSocket; SOCKADDR_IN sin, saUdpServ; BOOL fBroadcast = TRUE; char sendBuff [1024]; int nSize; int ncount = 0 ; IF (WsaStartup (MakeWord (1, 1), & WSADATA! = 0) // Permeated Winsocket Initialization {Printf ("CAN't Initiates Windows Socket! Program Stop./N": // Initialization Failback Return -1 Return -1;} SockListener = Socket (PF_INET, SOCK_DGRAM, 0); Setsockopt (Socklistener, Sol_Socket, So_Broadcast,
(Char *) & fbroadcast, sizeof (bool)); sin.sin_family = af_inet; sin.sin_port = htons (0); sin.sin_addr.s_addr = HTONL (INADDR_Any); if (Bind (Sock (Sock (SockAddr *) & Sin, SIZEOF (SIN))! = 0) {Printf ("" Can't Bind Socket To Local Port! Program Stop./N ": // Initialization Failure Returns -1 Return-1;} Saudpserv.sin_Family = AF_INET; Saudpserv. SIN_ADDR.S_ADDR = HTONL (INADDR_BROADCAST); Saudpserv.sin_Port = HTONS (7001); // The port is transmitted, can change nsize = sizeof (SockAddr_in) as needed; while (1) {sprintf (sendbuff, "message% D" , Ncount ); SendTo (SockListener, SendBuff, Lstrlen (SendBuff), 0, (SockAddr *) & Saudpserv, SizeOf (SockAddr_in)); Printf ("% s / n", sendbuff);} return 0;}
/
//receive
#include
int main (int argc, char * argv []) {WSADATA wsaData; // pointer to the information structure SOCKET sockListener WinSocket; SOCKADDR_IN sin, saClient; char cRecvBuff [1024]; int nSize, nbSize; int iAddrLen = sizeof (saClient) ; IF (WsaStartup (MakeWord (1, 1), & WSADATA! = 0) // Permeated Winsocket Initialization {Printf ("CAN't Initiates Windows Socket! Program Stop./N": // Initialization Failback Return -1 Return -1;} socklistener = socket (AF_INET, SOCK_DGRAM, 0); sin.sin_family = AF_INET; SIN.SIN_PORT = HTONS (7001); / / The send port used by the sending end can change Sin.sin_addr.s_addr = as needed HTONL (INADDR_Any); IF (Sock (Sockdr Far *) & Sin, SIZEOF (SIN))! = 0) {Printf ("Can't Bind Socket To Local Port! Program Stop./N" ;/// Initialization Failback Returns -1 return -1;} while (1) {nsize = sizeof (sockaddr_in); if ((Nbsize = Recvfrom (SockListener, CRECVBUFF, 1024, 0, (SockAddr Far *) & Saclient, & nsize) == SOCKET_ERROR ) {Printf ("Recive Error"); Break;} CRECVBUFF [Nbsize] = '/ 0'; Printf ("% S / N", CRECVBUFF);
} Return 0;}