广播通信代码框架:
1. 协议都是:
- SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
2. 服务端设置选项
- BOOL bBroadcast = TRUE;
- ::setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof(BOOL));
服务端代码:
- #include "InitSock.h"
- #include <stdio.h>
- VOID main()
- {
- CInitSock initSock;
- SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
- //设置广播就是设置这个选项
- BOOL bBroadcast = TRUE;
- ::setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof(BOOL));
- //设置广播地址
- SOCKADDR_IN bcast;
- bcast.sin_family = AF_INET;
- bcast.sin_port = htons(4567);
- bcast.sin_addr.S_un.S_addr = INADDR_BROADCAST; //::inet_addr("255.255.255.255");
- printf("begin send the data:\r\n");
- char sz[] = "this is the broadcast data";
- while(TRUE)
- {
- ::sendto(s, sz, sizeof(sz), 0, (sockaddr*)&bcast, sizeof(bcast));
- ::Sleep(5000);
- }
- }
- #include "InitSock.h"
- #include <stdio.h>
- VOID main()
- {
- CInitSock initSock;
- SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
- SOCKADDR_IN sin;
- sin.sin_family = AF_INET;
- sin.sin_port = ::htons(4567);
- sin.sin_addr.S_un.S_addr = INADDR_ANY;
- if (::bind(s, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR)
- {
- printf("bind error");
- return;
- }
- printf("begin recv the broadcast data:\r\n");
- char sz[256] = {0};
- SOCKADDR_IN addrRemote;
- int nLen = sizeof(SOCKADDR_IN); //这里必须设置成这个大小
- while (TRUE)
- {
- int nRet = ::recvfrom(s, sz, sizeof(sz), 0, (sockaddr*)&addrRemote, &nLen);
- if (nRet > 0)
- {
- sz[nRet] = '\0';
- printf(sz);
- }
- }
- }