Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1092850
  • 博文数量: 252
  • 博客积分: 4561
  • 博客等级: 上校
  • 技术积分: 2833
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-15 08:23
文章分类

全部博文(252)

文章存档

2015年(2)

2014年(1)

2013年(1)

2012年(16)

2011年(42)

2010年(67)

2009年(87)

2008年(36)

分类: C/C++

2011-07-27 10:34:38

#include
#include
#include
#include
#include
#include
#include

#define err(msg) perror(msg)
#define SA struct sockaddr

static int tcp_connect(const char *ip, int port)
{
        struct sockaddr_in addr;
        int fd;

        if ((fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
        {
                err("socket");
                goto out;
        }

        memset(&addr, '\0', sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port   = htons(port);
        if (inet_pton(AF_INET, ip, &addr.sin_addr) <= 0)
        {
                err("inet_pton");
                goto err;
        }

        if (connect(fd, (SA *)&addr, sizeof(addr)) == -1)
        {
                err("connect");
                goto err;
        }

        return fd;
err:
        close(fd);
out:
        return -1;
}

static void http_transaction(int fd)
{
        char buf[4096];
        int len;

        memset(buf, '\0', sizeof(buf));
        strcat(buf, "GET /index.html HTTP/1.1\r\n");
        strcat(buf, "Host: 127.0.0.1\r\n");
        strcat(buf, "If-Range: \"aa850b-1c7-4a9b1f759b6c0\"\r\n");
// or   strcat(buf, "Thu, 04 Aug 2011 18:15:31 GMT\r\n");
        strcat(buf, "Range: bytes=0-50, 100-150, 200-250, 300-350, 400-\r\n");
        strcat(buf, "User-Agent: firefox\r\n");
        strcat(buf, "Connection: close\r\n");
        strcat(buf, "\r\n");

        if (send(fd, buf, strlen(buf), 0) == -1)
        {
                err("send");
                goto out;
        }

        memset(buf, '\0', sizeof(buf));
        while ((len = recv(fd, buf, sizeof(buf), 0)) > 0)
        {
                write(STDOUT_FILENO, buf, len);
                memset(buf, '\0', sizeof(buf));
        }
out:
        return;
}

int main(void)
{
        int fd;

        if ((fd = tcp_connect("127.0.0.1", 80)) == -1)
        {
                err("tcp_connect");
                goto out;
        }

        http_transaction(fd);
        close(fd);
        return 0;
out:
        return -1;
}

阅读(1351) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~