在实际的网络应用中,只实现两点之间的的通讯是远远不够的。广播是能够同时实现多点通信的一种模式,这种通讯模式可以同时将信息发布到许多接收端点。

用于广播地址的约定是将IP所有的主机位都设置为1。例如127.255.255.255、192.168.0.255等。

下面是一段服务器的代码,它的作用是每隔4秒广播一次当前时间:

?[Copy to clipboard] View Code C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* srv.c:
 * Example Stock Index Broadcast :
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
 
/*
 * This function reports the error and
 * exits back to the shell :
 */
static void bail(const char *on_what) {
    fputs(strerror(errno),stderr);
    fputs(": ",stderr);
    fputs(on_what,stderr);
    fputc('\n',stderr);
    exit(1);
}
 
int
main(int argc,char **argv) {
    time_t td;
    int n;
    char buf[128];
    int z;           /* Status return code */
    int s;                       /* Socket */
    struct sockaddr_in addr_srv;/* AF_INET */
    int len_srv;               /* length  */
    struct sockaddr_in addr_bc;  /* AF_INET */
    int len_bc;                 /* length  */
    static int so_broadcast = 1;
    len_srv = sizeof (addr_srv);
    len_bc = sizeof (addr_bc);
 
    memset(&addr_srv,0,len_srv);
    addr_srv.sin_port=0;
    addr_srv.sin_family=AF_INET;
    addr_srv.sin_addr.s_addr=inet_addr("127.0.0.1");
 
    memset(&addr_bc,0,len_bc);
    addr_bc.sin_port=htons(9999);
    addr_bc.sin_family=AF_INET;
    addr_bc.sin_addr.s_addr=inet_addr("127.255.255.255");
 
    /*
     * Create a UDP socket to use :
     */
    s = socket(AF_INET,SOCK_DGRAM,0);
    if ( s == -1 )
        bail("socket()");
 
    /*
     * Allow broadcasts :
     */
    z = setsockopt(s,
        SOL_SOCKET,
        SO_BROADCAST,
        &so_broadcast,
        sizeof so_broadcast);
    if ( z == -1 )
        bail("setsockopt(SO_BROADCAST)");
 
    /*
     * Bind a address to our socket, so that
     * client programs can listen to this
     * server:
     */
    z = bind(s,
        (struct sockaddr *)&addr_srv,
        len_srv);
    if ( z == -1 )
        bail("bind()");
 
    for (;;) {
            time(&td);
            strftime(buf,sizeof(buf)," %Y %b %d %H:%M:%S  \n",localtime(&td));
            printf("%s\n",buf);
 
            z = sendto(s,
            buf,
            strlen(buf),
            0,
            (struct sockaddr *)&addr_bc,
            len_bc);
            if ( z == -1 )
                bail("sendto()");
 
        sleep(4);
    }
    return 0;
}