Lecture 10

From CS113

Socket Example

Example from the lecture in class:

#include<stdio.h>
#include<unistd.h>
#include<netinet/in.h>
#include<string.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> 
#include <stdlib.h>


int main(int argc, char **argv) {
    int sock;
    int addr = 0x480ecd67; // We got this by running "host www.google.com" on 
                           // the command line and converting one of the IP 
                           // addresses returned (72.14.205.103) into a 32-bit 
                           // integer by converting each octet into a hex value
                           // and OR'ing them together.
    int len;
    struct sockaddr_in sin;

    char buf[1024];

    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = htonl(addr);
    sin.sin_port = htons(80);

    if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) != 0) {
        fprintf(stderr, "Failed on connect.\n");
        exit(1);
    }

    strncpy(buf, "GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n", 1024);

    if (write(sock, buf, strlen(buf)) < strlen(buf)) {
        fprintf(stderr, "Failed on write.\n");
        exit(1);
    }

    while (1) {
        len = read(sock, buf, 1023);
        if (len <= 0) {
            break;
        }
        buf[len] = '\0';

        printf("%s", buf);
    }


}
Personal tools
Navigation