// tb.c - text based web browser // Usage: tb hostname page (for example www.yahoo.com /index.html ) #include #include #include #include // alarm() #include #include // socket() #include // htons(), struct in_addr #include // struct hostent int main(int argc, char **argv) { struct sockaddr_in s; struct hostent *h; int fd; char buf[1024]; int n; if (argc < 3) { fprintf(stderr, "To read web page: tb hostname /page (tb www.yahoo.com /index.html)\n"); exit(1); } alarm(5); // die after 5 seconds fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) perror("socket"), exit(1); s.sin_family = AF_INET; s.sin_port = htons(80); // port 80 is HTTP h = gethostbyname(argv[1]); // DNS lookup if (!h) perror(argv[1]), exit(1); // unknown host s.sin_addr.s_addr = ((struct in_addr*)(h->h_addr))->s_addr; if (connect(fd, (struct sockaddr*)&s, sizeof(s)) < 0) perror("connect"), exit(1); write(fd, "GET ", 4); // request web page using old HTTP 0.9 protocol write(fd, argv[2], strlen(argv[2])); write(fd, "\r\n", 2); while ((n = read(fd, buf, 1024)) > 0) // read response, copy to stdout write(1, buf, n); close(fd); return 0; }