linux-http小程序

本程序比较简单,主要是使用htpp协议的GET命令来获取web根目录的信息。

程序接收到web服务端返回的程序后,在终端中显示,并且在当前目录创建一个文本来记录信息。

 

上图:

 

 

 

 

源码:

#include <signal.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <errno.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	int sockfd,conn,filefd;
	int port = 80;
	char buffer[1024];
	char MsgBuf[2048];
	struct hostent *host;
	static struct sockaddr_in mysock;
	
	if(argc < 2){
		printf("usage:%s hostname/IP address\n",argv[0]);
		exit(1);
	}
	
	if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0){
		perror("socket error!\n");
		exit(1);
	}
	
	if((host = gethostbyname(argv[1])) == NULL){
		perror("gethostbyname error");
		exit(1);
	}
	
	mysock.sin_family = AF_INET;
	mysock.sin_addr =  *((struct in_addr *)host->h_addr);
	mysock.sin_port = htons(port);
	
	printf("Msg: %s(%s)\n",argv[1],inet_ntoa(mysock.sin_addr));
	conn = connect(sockfd,(struct sockaddr*)&mysock,sizeof(mysock));
	if(conn < 0){
		perror("connect error!\n");
		close(sockfd);
		exit(1);
	}
	memset(&buffer,0,1024);
	memset(&MsgBuf,0,sizeof(MsgBuf));
	printf("send packeting.. \n");
	//sprintf(buffer,"GET / HTTP/1.1\r\nHost:%s\r\nUser-Agent: Mozilla/5.0 (X11; Linux i686; rv:22.0) Gecko/20100101 Firefox/22.0 Iceweasel/22.0\r\n\r\n",argv[1]);
	sprintf(buffer,"GET / HTTP/1.1\r\nHost:%s\r\nUser-Agent: Mozilla/5.0\r\n\r\n",argv[1]);
	if(write(sockfd,buffer,sizeof(buffer))<0){
		perror("write error!\n");
		close(sockfd);
		exit(1);
	}
	//printf("send success!\n");
	if((read(sockfd,MsgBuf,sizeof(MsgBuf)))<0){
		perror("read error!\n");
		exit(1);
	}
	if((filefd = creat("http.txt",S_IRUSR|S_IWUSR))<0){
		perror("creat file errno\n");
	}
	if((write(filefd,MsgBuf,sizeof(MsgBuf)))<0){
		perror("write file errno\n");
	}
	printf("%s",MsgBuf);
	close(sockfd);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值