#include<stdio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<netdb.h>
#include<errno.h>
int find_str(char* str1,char* str2)
{
int i,j,flag=-1;
for(i=0,j=0;str1[i]!=NULL;i++)
{
while(str1[i]==str2[j]&&str1[i]&&str2[j])
{
i++;
j++;
if(str2[j]==NULL)
{
flag=i-j;
return flag;
}
}
j=0;
}
return flag;
}
int main(int argc, char *argv[])
{
int socket_desc;
struct sockaddr_in server;
char *www ="180.101.49.11";
//Create socket
socket_desc = socket(AF_INET, SOCK_STREAM , 0);
if (socket_desc == -1) {
printf("Could not create socket");
}
server.sin_addr.s_addr = inet_addr(www);
server.sin_family = AF_INET;
server.sin_port = htons(80);
//Connect to remote server
if (connect(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0) {
printf("connect error: %s", errno);
return 1;
}
puts("Connected\n");
char *message = "GET /?st=1 HTTP/1.1\r\nHost:www.baidu.com\r\nConnection:Close\r\n\r\n";
//向服务器发送数据
if (send(socket_desc, message, strlen(message) , 0) < 0) {
puts("Send failed");
return 1;
}
puts("Data Send\n");
struct timeval timeout = {3, 0};
setsockopt(socket_desc, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval));
//Receive a reply from the server
//loop
int size_recv, total_size = 0;
char chunk[512];
char *start = "";
char *end = "";
char *data = "";
char ddd[512] = "";
int r = 0, nread = 0;
memset(chunk , 0 , 512);
while(1) {
//clear the variable
//获取数据
if ((size_recv = recv(socket_desc, chunk+ nread, 512- nread, 0) ) == -1) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
// printf("recv timeout ...\n");
break;
} else if (errno == EINTR) {
// printf("interrupt by signal...\n");
continue;
} else if (errno == ENOENT) {
// printf("recv RST segement...\n");
break;
} else {
// printf("unknown error: %d\n", errno);
exit(1);
}
} else if (size_recv == 0) {
// printf("peer closed ...\n");
break;
} else {
nread+=size_recv;
total_size += size_recv;
// printf("%s" , chunk);
}
}
printf("LZG[%s]" , chunk);
printf("Reply received, total_size = %d bytes\n", total_size);
return 0;
}
03-01
573
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-18