c语言实现的http请求

/*
 * =====================================================================================
 *
 * Filename: RequestHttp.c
 *
 * Description:
 *
 * Version: 1.0
 * Created: 2006年12月31日 13時14分25秒 UTC
 * Revision: none
 * Compiler: gcc RequestHttp.c -o RequestHttp
 *
 * Author: Flw10000, flw10000@163.com
 *
 * =====================================================================================
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>

#define BUFSIZE 1024
#define DestIp "xx.xx.xx.xx"
#define DestPort 9000
#define Req "GET /index.html HTTP/1.1\r\nHost: xx.xx.xx.xx\r\nConnection: Close\r\n\r\n"
#define ReqLen sizeof(Req)

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 */

                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(structsockaddr)) == -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(>= i){
                                                break;
                                }
                                strResponse[i]='\0';
                                printf(strResponse);

                }

                /* Close the connection */
                close(sockfd);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值