Debian Codegraph @

listings/chapter-5/socket-inet.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <netinet/in.h>
10 #include <netdb.h>
11 #include <sys/socket.h>
12 #include <unistd.h>
13 #include <string.h>
14
15 /* Print the contents of the home page for the server's socket.
16 Return an indication of success. */
17
18 void get_home_page (int socket_fd)
19 {
20 char buffer[10000];
21 ssize_t number_characters_read;
22
23 /* Send the HTTP GET command for the home page. */
24 sprintf (buffer, "GET /\n");
25 write (socket_fd, buffer, strlen (buffer));
26 /* Read from the socket. read may not return all the data at one
27 time, so keep trying until we run out. */
28 while (1) {
29 number_characters_read = read (socket_fd, buffer, 10000);
30 if (number_characters_read == 0)
31 return;
32 /* Write the data to standard output. */
33 fwrite (buffer, sizeof (char), number_characters_read, stdout);
34 }
35 }
36
37 int main (int argc, char* const argv[])
38 {
39 int socket_fd;
40 struct sockaddr_in name;
41 struct hostent* hostinfo;
42
43 /* Create the socket. */
44 socket_fd = socket (PF_INET, SOCK_STREAM, 0);
45 /* Store the server's name in the socket address. */
46 name.sin_family = AF_INET;
47 /* Convert from strings to numbers. */
48 hostinfo = gethostbyname (argv[1]);
49 if (hostinfo == NULL)
50 return 1;
51 else
52 name.sin_addr = *((struct in_addr *) hostinfo->h_addr);
53 /* Web servers use port 80. */
54 name.sin_port = htons (80);
55
56 /* Connect to the web server */
57 if (connect (socket_fd, &name, sizeof (struct sockaddr_in)) == -1) {
58 perror ("connect");
59 return 1;
60 }
61 /* Retrieve the server's home page. */
62 get_home_page (socket_fd);
63
64 return 0;
65 }