WWW超文本源码浏览器

Linux下的C程序:读取远程服务器上的网页源码。

/*
	功能:WWW超文本源码浏览器
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

// connect to domain at port
int htconnect(char *domain, int port)
{
	int white_sock;
	struct hostent *site;
	struct sockaddr_in me;

	site = gethostbyname(domain);
	if(site == NULL)
		return -2;

	white_sock = socket(AF_INET, SOCK_STREAM, 0);
	if(white_sock < 0)
		return -1;

	memset(&me, 0, sizeof(struct sockaddr_in));
	memcpy(&me.sin_addr, site->h_addr_list[0], site->h_length);
	me.sin_family = AF_INET;
	me.sin_port = htons(port);

	return (connect(white_sock, (struct sockaddr*)&me, sizeof(struct sockaddr)) < 0) ? 1 : white_sock;
}

// send formatted string to the port
int htsend(int sock, char *fmt, ...)
{
	char buf[1024];
	va_list argptr;

	va_start(argptr, fmt);
	vsprintf(buf, fmt, argptr);
	va_end(argptr);

	return send(sock, buf, strlen(buf), 0);
}

void main(int argc, char **argv)
{
	int black_sock;
	char bugs_bunny[3];

	if(argc < 2)
	{
		printf("Usage:\t %s <host>\n", argv[0]);
		return ;
	}
	black_sock = htconnect(argv[1], 80);
	if(black_sock < 0)
	{
		printf("Socket connect error\n");
		return ;
	}
	htsend(black_sock, "GET /joe.html HTTP/1.0%c", 10);		// [/joe.html]: requested page on the server
	htsend(black_sock, "Host:%s%c", argv[1], 10);			// 10: refer to <Enter> key
	htsend(black_sock, "%c", 10);
	while(read(black_sock, bugs_bunny, 1) > 0)				// read one byte every time
	{
		printf("%c", bugs_bunny[0]);						// print data from server
	}
	close(black_sock);										// close socket
	printf("\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值