Skip to content

Instantly share code, notes, and snippets.

@water-air-flash
Forked from cwt8805/HttpRequest.c
Created September 23, 2016 08:52
Show Gist options
  • Select an option

  • Save water-air-flash/e2ed6d9a458f1707fc625fa25e0b9b12 to your computer and use it in GitHub Desktop.

Select an option

Save water-air-flash/e2ed6d9a458f1707fc625fa25e0b9b12 to your computer and use it in GitHub Desktop.

Revisions

  1. @cwt8805 cwt8805 created this gist Oct 9, 2014.
    47 changes: 47 additions & 0 deletions HttpRequest.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    #include <WinSock2.h>
    #include <stdio.h>

    #pragma comment(lib,"ws2_32.lib")

    int main()
    {
    //构造socket
    WSADATA data;
    SOCKET sock;
    if (WSAStartup(MAKEWORD(2, 2), &data) != 0) return -1;
    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock == INVALID_SOCKET)
    {
    printf("invalid socket !");
    return -1;
    }

    //连接服务器
    SOCKADDR_IN addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    if (connect(sock, (SOCKADDR *)&addr, sizeof(addr)) == SOCKET_ERROR)
    {
    printf("connect error !");
    closesocket(sock);
    return -1;
    }

    //发送HTTP请求
    char buf[1024];
    int count = sprintf(buf, "GET /main.c HTTP/1.1\r\nhost:%s\r\n\r\n", "127.0.0.1");
    send(sock, buf, count, 0);

    //接收回复并打印
    count = recv(sock, buf, 1024, 0);
    if (count > 0)
    {
    buf[count] = 0;
    printf(buf);
    }

    closesocket(sock);
    WSACleanup();
    return 0;
    }