最新消息:

Linux Socket 学习笔记20-UDP广播客户端

Linux admin 3418浏览 0评论

下面是客户端代码,它接收服务器端的消息:

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
/* 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) {
    char buf[128];
    int z;           /* Status return code */
    int s;                       /* Socket */
    struct sockaddr_in addr;
    static int so_reuseaddr = 1;
    int len = sizeof (addr);
 
    memset(&addr,0,len);
    addr.sin_port=htons(9999);
    addr.sin_family=AF_INET;
    addr.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_REUSEADDR,
        &so_reuseaddr,
        sizeof so_reuseaddr);
    if ( z == -1 )
        bail("setsockopt(so_reuseaddr)");
 
    /*
     * Bind a address to our socket, so that
     * client programs can listen to this
     * server:
     */
    z = bind(s,
        (struct sockaddr *)&addr,
        len);
    if ( z == -1 )
        bail("bind()");
 
    for (;;) {
            z = recvfrom(s,
            buf,
            sizeof(buf),
            0,
            (struct sockaddr *)&addr,
            &len);
            if ( z == -1 )
                bail("recvfrom()");
 
            printf("%s",buf);
 
    }
    return 0;
}

转载请注明:爱开源 » Linux Socket 学习笔记20-UDP广播客户端

您必须 登录 才能发表评论!