Modifiche varie e ripulitura esempi. Trattata accept4.
[gapil.git] / listati / TCP_daytime.c
1 #include <stdlib.h>   /* predefined types */
2 #include <unistd.h>      /* include unix standard library */
3 #include <arpa/inet.h>   /* IP addresses conversion utilities */
4 #include <sys/socket.h>  /* socket library */
5 #include <stdio.h>       /* include standard I/O library */
6 #include <string.h>      /* C strings library */
7
8 int main(int argc, char *argv[])
9 {
10     int sock_fd;
11     int i, nread;
12     struct sockaddr_in serv_add;
13     char buffer[MAXLINE];
14      ...
15     /* create socket */
16     if ( (sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
17         perror("Socket creation error");
18         return -1;
19     }
20     /* initialize address */
21     memset((void *) &serv_add, 0, sizeof(serv_add)); /* clear server address */
22     serv_add.sin_family = AF_INET;                   /* address type is INET */
23     serv_add.sin_port = htons(13);                   /* daytime post is 13 */
24     /* build address using inet_pton */
25     if ( (inet_pton(AF_INET, argv[optind], &serv_add.sin_addr)) <= 0) {
26         perror("Address creation error");
27         return -1;
28     }
29     /* extablish connection */
30     if (connect(sock_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
31         perror("Connection error");
32         return -1;
33     }
34     /* read daytime from server */
35     while ( (nread = read(sock_fd, buffer, MAXLINE)) > 0) {
36         buffer[nread]=0;
37         if (fputs(buffer, stdout) == EOF) {          /* write daytime */
38             perror("fputs error");
39             return -1;
40         }
41     }
42     /* error on read */
43     if (nread < 0) {
44         perror("Read error");
45         return -1;
46     }
47     /* normal exit */
48     return 0;
49 }