⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 http1.c

📁 Qt 4C++.GUI.Programming.with.Qt.4.chm
💻 C
字号:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>




#define BUFSIZE 1024
#define DestIp "211.94.144.100"    //"www.baidu.com"
#define DestPort 80
#define Req "GET /index.html HTTP/1.1\r\nHost: 211.94.144.100\r\nConnection: Close\r\n\r\n"
#define ReqLen sizeof(Req)



unsigned long dns(const char* host_name)
{
    struct hostent* host = gethostbyname(host_name);
    struct in_addr addr;
    char ** pp;

    pp = host->h_addr_list;
    if (*pp!=NULL)
    {
        addr.s_addr = *((unsigned int *)*pp);
        printf("address is %s\n",inet_ntoa(addr));
        pp++;

        return addr.s_addr;
    }
    return 0;
}

int main(int argc, char *argv[])
{
    ssize_t i;
    int nRequestLen;

    char strResponse[BUFSIZE]={0};
    char strRequest[BUFSIZE]={0};


    int sockfd, numbytes;
    struct sockaddr_in dest_addr; /* connector's address information */

    dns(DestIp);

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket");
        exit(1);
    }

    dest_addr.sin_family = AF_INET; /* host byte order */
    dest_addr.sin_port = htons(DestPort); /* short, network byte order */
    dest_addr.sin_addr.s_addr = inet_addr(DestIp);

    /* Create and setup the connection */
    if (connect(sockfd, (struct sockaddr *)&dest_addr,sizeof(struct sockaddr)) == -1)
    {
        perror("connect");
        exit(1);
    }

    /* Send the request */
    strncpy(strRequest, Req,ReqLen);
    nRequestLen = ReqLen;
    if (write(sockfd,strRequest,nRequestLen) == -1)
    {
        perror("write");
        exit(1);
    }

    /* Read in the response */
    while (1)
    {
        i = read(sockfd,strResponse,BUFSIZE-1);
        if (0 >= i)
        {
            break;
        }
        strResponse[i]='\0';
        printf(strResponse);

    }

    /* Close the connection */
    close(sockfd);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -