socket实现最最最简单的http请求的数据


/* For sockaddr_in */
#include <netinet/in.h>
/* For socket functions */
#include <sys/socket.h>
/* For gethostbyname */
#include <netdb.h>

#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
	if(argc != 2)
	{
		printf("parameter error!\n");
		return -1;
	}
	char query[1024];
	memset(query, 0x00,sizeof(query));
	snprintf(query, sizeof(query), "GET / HTTP/1.0\r\n"
									"%s\r\n"
									"\r\n",
									argv[1]);
	printf("query = %s\n",query);
	
	
	char hostname[128];
	memset(hostname, 0x00,sizeof(hostname));	
	strcpy(hostname, argv[1]);
	
	struct sockaddr_in sin;
	struct hostent *h;
	const char *cp;
	int fd;
	ssize_t n_written, remaining;
	char buf[1024];

	/* Look up the IP address for the hostname.   Watch out; this isn't
	   threadsafe on most platforms. */
	h = gethostbyname(hostname);
	if (!h) {
		fprintf(stderr, "Couldn't lookup %s: %s", hostname, hstrerror(h_errno));
		return 1;
	}
	if (h->h_addrtype != AF_INET) {
		fprintf(stderr, "No ipv6 support, sorry.");
		return 1;
	}    /* Write the query. */
	/* XXX Can send succeed partially? */
	cp = query;
	remaining = strlen(query);
	
	fd = socket(AF_INET,SOCK_STREAM,0);

	struct sockaddr_in srvaddr;
	srvaddr.sin_family = AF_INET;
	srvaddr.sin_port = htons(80);
	char ip[128];
	memset(ip, 0x00,sizeof(ip));
	inet_ntop(h->h_addrtype, *(h->h_addr_list), ip, sizeof(ip));
	printf("ip = %s\n",ip);
	
	srvaddr.sin_addr.s_addr = inet_addr(ip);
        //srvaddr.sin_addr = *(struct in_addr*)h->h_addr;

	if (connect(fd, (struct sockaddr*) (&srvaddr), sizeof(srvaddr)) < 0) 
	{
		perror("fun socket:");
		exit(0);
	}

	while (remaining) {
	  n_written = send(fd, cp, remaining, 0);
	  if (n_written <= 0) {
		perror("send");
		return 1;
	  }
	  remaining -= n_written;
	  cp += n_written;
	}


	/* Get an answer back. */
	while (1) {
		ssize_t result = recv(fd, buf, sizeof(buf), 0);
		if (result == 0) {
			break;
		} else if (result < 0) {
			perror("recv");
			close(fd);
			return 1;
		}
		fwrite(buf, 1, result, stdout);
	}


	close(fd);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值