📄 gosina.c
字号:
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<netdb.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<netinet/in.h>
#include <stdarg.h>
#define MAXDATASIZE 8000
#define PORT 80
int main (int argc,char *argv[])
//int main (void)
{
int sockfd,numbytes;
char buf[MAXDATASIZE];
char *sendbuf = "GET http://";
//char *sendbuf = "GET /index.html HTTP/1.1\r\nAccept:text/html\r\nReferer:http://" ;
struct hostent *he;//he为hostent 类型的数据结构,用来存放所获取的主机信息
struct sockaddr_in their_addr;//存放主机信息
if(argc!=2)
{
printf("too few parameter, no URL!\n");
exit(1);
}
printf ("step 1 !\n");
//获取主机信息,根据域名得到IP地址
if((he = gethostbyname(argv[1])) == NULL)
{
printf("gethostbyname error");
exit(1);
}
//建立流式套接字描述符
printf ("step 2 ! \n");
if((sockfd = socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("socked error");
exit(1);
printf ("error 3 !\n");
}
printf ("socket right !\n");
//给定远端主机信息
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(PORT);
their_addr.sin_addr = *((struct in_addr*)he->h_addr);
//their_addr.sin_addr.s_addr = inet_addr("211.154.211.220");
bzero(&(their_addr.sin_zero),8);
printf("you connected IP is:%s\n",inet_ntoa(their_addr.sin_addr));
//建立连接
if(connect(sockfd,(struct sockaddr*)&their_addr,sizeof(struct sockaddr)) == -1)
{
printf("connect error! \n");
exit(1);
}
printf ("connect right !\n");
//发送请求
//sprintf(sendbuf,"%s%s",sendbuf,"\r\n");
//sprintf(sendbuf, "%s%s",sendbuf,argv[1]);
//sprintf(sendbuf,"%s%s",sendbuf," HTTP/1.1\r\n");
sprintf(sendbuf,"%s%s",sendbuf,inet_ntoa(their_addr.sin_addr));
sprintf(sendbuf,"%s%s",sendbuf, " HTTP/1.1\r\nAccept:text/html\r\nReferer:http://");
sprintf(sendbuf,"%s%s",sendbuf,inet_ntoa(their_addr.sin_addr));
sprintf(sendbuf,"%s%s",sendbuf,":80\r\nHost:");
sprintf(sendbuf,"%s%s",sendbuf,inet_ntoa(their_addr.sin_addr));
sprintf(sendbuf,"%s%s",sendbuf,":80\r\nConnection:Keep-Alive\r\n");
sprintf(sendbuf,"%s%s",sendbuf,"\r\n");
if(send(sockfd,sendbuf,strlen(sendbuf),0)==-1)
{
printf("send error \n");
exit(1);
}
printf ("your send content is:\n%s\n",sendbuf,"wait for response ....!\n");
//接受返回的信息
if((numbytes = recv(sockfd,buf,MAXDATASIZE,0))==-1)
{
printf("recv error \n");
exit(1);
}
printf ("receive num is %d !\n",numbytes);
buf[numbytes] = '\0';
printf("Received :%s\n",buf);
close(sockfd);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -