c++ socket 发送HTTP请求

 

c++ socket 发送HTTP请求

#include <iostream>;
using namespace std;

#include <sys/types.h>;
#include <sys/stat.h>;
#include <fcntl.h>;
#include <sys/socket.h>;
#include <sys/stat.h>;
#include <unistd.h>;
#include <stdlib.h>;
#include <netdb.h>;
#include <arpa/inet.h>;
#include <netinet/in.h>;
#include <string.h>;
#include <errno.h>;

int main(int argc, char* argv[])
{
        if (argc != 3) {
                cout << "useage: " << argv[0] << " <ipaddress>;" << " <port>;" << endl;
                cout << "errno= " << errno << endl;
                exit(1);
        }

        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) {
                cout << "Can not create socket!" << endl;
                cout << "errno= " << errno << endl;
                exit(2);
        }

        struct sockaddr_in cliaddr;
        int len = sizeof(cliaddr);
        memset(&cliaddr, 0, len);
        cliaddr.sin_family = AF_INET;
        cliaddr.sin_addr.s_addr = inet_addr(argv[1]);
        cliaddr.sin_port = htons(atoi(argv[2]));

        if((connect(sockfd, (sockaddr*)&cliaddr, len)) < 0) {
                cout << "Can not create connect!" << endl;       
                cout << "errno= " << errno << endl;
                exit(3);
        }

        char buf[2048];
        strcpy(buf, "GET / HTTP/1.0 \r\n\r\n");
       
        if (write(sockfd, buf, strlen(buf)) < 0) {
                cout << "Write error!" << endl;
                cout << "errno= " << endl;
                exit(4);       
        }

        memset(buf, 0, 2048);
        if (read(sockfd, buf, 2048) < 0) {
                cout << "Read error!" << endl;
                cout << "errno= " << endl;
                exit(5);       
        }

        int ok = open("test.html", O_WRONLY|O_CREAT, 0777);
        if (ok < 0) {
                cout << "Can not open test.html, please try again!" << endl;
                cout << "errno= " << errno << endl;
                exit(6);
        }
       
        if (write(ok, buf, strlen(buf)) < 0) {
                cout << "Write error!" << endl;
                cout << "errno= " << endl;
                exit(7);       
        }

        cout << buf << endl;

        close(sockfd);
        close(ok);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值