Socket网络编程的广播用的地址是255.255.255.255,广播数据不会被路由器转发,限定于局域网内,否则就是网络风暴了。
广播的代码比较简单,直接参考单播/组播的例子写一个。
Server端的流程如下:
- 调用socket()打开一个Socket
- 调用bind()指定Port信息
- 调用setsockopt()加入广播
- 调用recvfrom()阻塞接收
- 最后,调用close()关闭Socket
#include "stdio.h" /* pritnf() */
#include "stdLib.h" /* malloc() */
#include "sockLib.h" /* socket() */
#include "inetLib.h" /* struct sockaddr_in */
#define HOST_PORT 60000
#define MIN_SIZE 10
#define MIN_TIMES 10
void broadServer (int port, int size, int times)
{
struct sockaddr_in localAddr;
struct sockaddr_in peerAddr;
int addrSize = sizeof(struct sockaddr);
int opt = 1;
int fd;
int num;
char *buffer;
if(port <= 2000) port = HOST_PORT;
if(size <= 0) size = MIN_SIZE;
if(times <= 0) times = MIN_TIMES;
printf (" broadServer: try to receive %d chars from port %d\n", size, port);
/* 打开Socket */
fd = socket (AF_INET, SOCK_DGRAM, 0);
/* 指定本地地址信息 */
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons (port);
localAddr.sin_addr.s_addr = INADDR_ANY;
bind (fd, (struct sockaddr *)&localAddr, sizeof(struct sockaddr));
/* 加入广播 */
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(int));
buffer = (char *)malloc (size);
while ((times--)>0)
{
/* 接收广播数据 */
num = recvfrom (fd, buffer, size, 0,
(struct sockaddr *)&peerAddr, &addrSize);
if (num < 0) break;
printf (" broadServer: recv %d chars from %s\n",
num, inet_ntoa(peerAddr.sin_addr));
}
/* 关闭Socket */
close (fd);
free (buffer);
printf (" broadServer: end\n");
}
Client端的流程如下:
- 调用socket()打开一个Socket
- 指定广播地址和Port信息
- 调用sendto()发送数据
- 最后,调用close()关闭Socket
#include "stdio.h" /* pritnf() */ #include "stdLib.h" /* malloc() */ #include "sockLib.h" /* socket() */ #include "inetLib.h" /* struct sockaddr_in */ #define HOST_PORT 60000 #define MIN_SIZE 1 #define MIN_TIMES 1 void broadClient (int port, int size, int times) { struct sockaddr_in serverAddr; int opt = 1; int fd; char *buffer; int num; if(port <= 2000) port = HOST_PORT; if(size <= 0) size = MIN_SIZE; if(times<= 0) times= MIN_TIMES; buffer = (char *)malloc(size); for(num=0; num<size; num++) buffer[num] = (num%26)+'a'; /* 服务器地址信息 */ serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons (port); serverAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST); printf (" broadClient: try to send %d chars %d times to %s:%d\n", size, times, inet_ntoa(serverAddr.sin_addr), port); /* 打开Socket */ fd = socket (AF_INET, SOCK_DGRAM, 0); while ((times--)>0) { /* 发送数据到BroadCast Server */ num = sendto(fd, buffer, size, 0, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr)); printf (" broadClient: send %d chars\n", num); } /* 关闭Socket */ close (fd); free (buffer); printf (" broadClient: send finished\n"); }
测试结果如下: