APUE Learning Example Source Code
guowenxue
2023-11-06 f63647218e192628aa8598d504e064529398f159
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <pthread.h>
#include <getopt.h>
#include <libgen.h> 
#include <sys/types.h>   
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h> 
 
 
typedef struct link_node_s 
{
    int                   fd;  
    struct link_node_s   *next;
} link_node_t;  
 
 
static inline void msleep(unsigned long ms);
static inline void print_usage(char *progname);
int socket_server_init(char *listen_ip, int listen_port);
int add_fd_list(link_node_t  **head, int fd);
link_node_t *list_remove_node(link_node_t  **head, link_node_t *node);
 
 
int main(int argc, char **argv)
{
    int                       listenfd, connfd;
    int                       serv_port = 0;
    int                       daemon_run = 0;
    char                     *progname = NULL;
    int                       opt;
    fd_set                    rdset; 
    link_node_t              *client_list = NULL; /* client fd link list, we will not use arrary for it get max client limite */
    link_node_t              *node;
    int                       rv;
    int                       i;
    int                       maxfd=0;
    char                      buf[1024];
 
    struct option             long_options[] = 
    {   
        {"daemon", no_argument, NULL, 'b'},
        {"port", required_argument, NULL, 'p'},
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };  
 
    progname = basename(argv[0]);
 
    /*  Parser the command line parameters */
    while ((opt = getopt_long(argc, argv, "bp:h", long_options, NULL)) != -1) 
    {   
        switch (opt)
        {   
            case 'b':
                daemon_run=1;
                break;
 
            case 'p':
                serv_port = atoi(optarg);
                break;
 
            case 'h':  /*  Get help information */
                print_usage(progname);
                return EXIT_SUCCESS;
 
            default:
                break;
        }   
    }   
 
    if( !serv_port ) 
    {   
        print_usage(progname);
        return -1; 
    }
 
    if( (listenfd=socket_server_init(NULL, serv_port)) < 0 )
    {
        printf("ERROR: %s server listen on port %d failure\n", argv[0],serv_port);
        return -2;
    }
    printf("%s server start to listen on port %d\n", argv[0],serv_port);
 
 
    /* set program running on background */
    if( daemon_run ) 
    {
        daemon(0, 0);
    }
 
    printf("add listen socket[%d] into client list\n", listenfd );
    add_fd_list(&client_list, listenfd);
 
    for ( ; ; ) 
    {
        FD_ZERO(&rdset);
           for( node=client_list; node!=NULL; node=node->next ) 
    {
        //printf("Add socket[%d] in select readset\n", node->fd);
        maxfd = node->fd>maxfd ? node->fd : maxfd;
        FD_SET(node->fd, &rdset); 
    }
 
    /* program will blocked here */
        rv = select(maxfd+1, &rdset, NULL, NULL, NULL); 
        if(rv < 0)
        {
            printf("select failure: %s\n", strerror(errno));
            break;
        }
        else if(rv == 0)
        {
            printf("select get timeout\n");
            continue;
        }
 
    /* listen socket get event means new client start connect now */
        if ( FD_ISSET(listenfd, &rdset) ) 
        {
            if( (connfd=accept(listenfd, (struct sockaddr *)NULL, NULL)) < 0)
            {
                printf("accept new client failure: %s\n", strerror(errno));
                continue;
            }
 
            printf("accept new client[%d] and add it into client list\n", connfd );
            add_fd_list(&client_list, connfd);
        }
        else /* data arrive from already connected client */
        {
        node = client_list;
               while( node != NULL ) 
        {
        if( !FD_ISSET(node->fd, &rdset) )
        {
            node = node->next;
            continue;
        }
 
                if( (rv=read(node->fd, buf, sizeof(buf))) <= 0)
                {
                   printf("socket[%d] read failure or get disconncet.\n", node->fd);
           /* list_remove_node will return the previous node */
           node = list_remove_node(&client_list, node); 
        }
        else
        {
            printf("socket[%d] read get %d bytes data\n", node->fd, rv);
 
            /* convert letter from lowercase to uppercase */
            for(i=0; i<rv; i++)
            buf[i]=toupper(buf[i]);
 
                    if( write(node->fd, buf, rv) < 0 )
            {
                printf("socket[%d] write failure: %s\n", node->fd, strerror(errno));
                   /* list_remove_node will return the previous node */
                node = list_remove_node(&client_list, node);
            }
        }
 
        if( node != NULL )
        {
            node = node->next;
        }
            } /* while( node != NULL ) */
        }
    }
 
CleanUp:
    close(listenfd); 
    return 0;
}
 
 
static inline void msleep(unsigned long ms) 
{
    struct timeval       tv; 
 
    tv.tv_sec = ms/1000;
    tv.tv_usec = (ms%1000)*1000; 
    
    select(0, NULL, NULL, NULL, &tv);
}
 
 
static inline void print_usage(char *progname)
    printf("Usage: %s [OPTION]...\n", progname);
    
    printf(" %s is a socket server program, which used to verify client and echo back string from it\n", progname); 
    printf("\nMandatory arguments to long options are mandatory for short options too:\n"); 
    
    printf(" -b[daemon ]  set program running on background\n");
    printf(" -p[port    ]  Socket server port address\n");
    printf(" -h[help    ]  Display this help information\n");
    
 
    printf("\nExample: %s -b -p 8900\n", progname);
    return ;
}
 
 
int socket_server_init(char *listen_ip, int listen_port)
{
    struct sockaddr_in        servaddr;
    int                       rv = 0;
    int                       on = 1;
    int                       listenfd;
 
    if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("Use socket() to create a TCP socket failure: %s\n", strerror(errno));
        return -1;
    }
 
    /* Set socket port reuseable, fix 'Address already in use' bug when socket server restart */
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
 
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;   
    servaddr.sin_port = htons(listen_port); 
 
    if( !listen_ip )  /* Listen all the local IP address */
    {
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);  
    }
    else /* listen the specified IP address  */
    {
        if (inet_pton(AF_INET, listen_ip, &servaddr.sin_addr) <= 0)
        {
            printf("inet_pton() set listen IP address failure.\n");
        rv = -2;
            goto CleanUp;
        }
    }
 
 
    if(bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
    {
        printf("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        rv = -3;
        goto CleanUp;
    }
 
    if(listen(listenfd, 13) < 0)
    {
        printf("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        rv = -4;
        goto CleanUp;
    }
 
CleanUp:
    if(rv<0)
        close(listenfd);
    else
        rv = listenfd;
 
    return rv;
}
 
int add_fd_list(link_node_t  **head, int fd)
{
    link_node_t          *node;
    link_node_t          *tmp;
 
    if( NULL == (node=(link_node_t *)malloc(sizeof(*node))) ) 
    {
        printf("malloc for new node failure\n");
        return -1;
    }
 
    memset(node, 0, sizeof(*node));
    node->fd = fd;
    node->next = NULL;
 
    if( *head == NULL )
    {
        *head = node;
        return 0;
    }
 
    tmp = *head;
    while( tmp->next != NULL )
    {
        tmp=tmp->next;
    }
 
    tmp->next = node;
}
 
/* list_remove_node will return the previous node */
link_node_t *list_remove_node(link_node_t  **head, link_node_t *node)
{
    link_node_t         *prev;
 
    close(node->fd);
 
    if( node == *head )
    {
     *head = NULL;
     free(node);
     return NULL;
    }
    else
    {
        for(prev=*head; prev!=NULL; prev=prev->next) 
        {
       if(prev->next == node) 
       { 
           prev->next = node->next;
           free(node);
           return prev;
       }
           }
    }
}