纯C编写HTTP Client

纯C编写HTTP Client

本文使用纯C在Windows下编写一个简单的HTTP Client,废话不说,直接代码:

#include 
#include 
#pragma comment(lib, "ws2_32.lib")
char sndBuf[1024] = {0};//发送缓冲
char rcvBuf[1<<14] = {0};//接收缓冲

int main(int argc, char **argv){
    SOCKET sSocket = INVALID_SOCKET;
    SOCKADDR_IN stSvrAddrIn = {0}; //服务器端地址
    int num = 0;
    int nRet = SOCKET_ERROR;
    struct hostent *remoteHost;//域名
    struct in_addr addr;//ip
    //u_long ul = 1;
    WSADATA wsaData;

    if(argc < 2){
        printf("usage: %s \n", argv[0]);
        return 1;
    }
    nRet = WSAStartup(MAKEWORD(2, 0), &wsaData);
    if(nRet!=0){
        printf("WSAStartup failed!\n");
        return 1;
    }
    remoteHost = gethostbyname(argv[1]); //获取ip地址
    if(remoteHost == NULL){
        printf("Gethostbyname Error:%d\n",WSAGetLastError());
        return 1;
    }
    addr.s_addr = *(u_long*)remoteHost->h_addr;
    //printf("ip: %s\n",inet_ntoa(addr));

    //HTTP 消息构造开始,这是程序的关键之处
    sprintf(sndBuf, "GET / HTTP/1.1\r\n"
        "Host:%s\r\n\r\n",argv[1]);
    sSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    stSvrAddrIn.sin_family = AF_INET;
    stSvrAddrIn.sin_port = htons(80);
    stSvrAddrIn.sin_addr = addr;
    //ioctl(sockfd, FIONBIO, &ul); //设置为非阻塞模式select
    nRet = connect(sSocket, (SOCKADDR*)&stSvrAddrIn, sizeof(SOCKADDR));
    if (SOCKET_ERROR == nRet){
        printf("Connect failed!\n");
        return 1;
    }
    //发送HTTP请求消息
    send(sSocket, (char*)sndBuf, sizeof(sndBuf), 0);
    //接收HTTP响应消息
    while(1)
    {
        num = recv(sSocket, rcvBuf, sizeof(rcvBuf), 0);
        printf("%s\n%d", rcvBuf,num);
        if(0>=num){
            break;
        }
    }
    return 0;
}

你可能感兴趣的:(HTTP)