The code is simple to send the C language to send HTTP requests, but i= read (SOCKFD, buf, BUFSIZE-1); can run normally,
Replace with i= Read (SOCKFD, buf, BUFSIZE-1); After the program exits, do not know what reason, to seek answers.
#include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <time.h> #include <errno.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <unistd.h > #include <sys/wait.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h > #define IPSTR "180.97.33.107" #define PORT 80#define BUFSIZE 1024x768 * 2int Read (int fd, char *buf, int count) { int nread, Totlen = 0; while (Totlen! = count) {nread = Read (FD, buf, Count-totlen); if (nread = = 0) return totlen; if (nread = =-1) return-1; Totlen + = Nread; BUF + = Nread; } return Totlen;} int main (int argc, char **argv) {int SOCKFD, ret, I, H; struct sockaddr_in servaddr; Char str1[4096], buf[bufsize]; Socklen_t Len; Fd_set T_set1; struct Timeval TV; if ((SOCKFD = socket (af_inet, sock_stream, 0)) < 0){printf ("---socket error!\n"); Exit (0); }; Bzero (&servaddr, sizeof (SERVADDR)); servaddr.sin_family = af_inet; Servaddr.sin_port = htons (port); if (Inet_pton (Af_inet, Ipstr, &servaddr.sin_addr) <= 0) {printf ("--inet_pton error!\n"); Exit (0); }; if (Connect (SOCKFD, (struct sockaddr *) &servaddr, sizeof (SERVADDR)) < 0) {printf ("Connect error!\n") ; Exit (0); } memset (str1, 0, 4096); strcat (str1, "get/http/1.1\n"); strcat (str1, "host:www.baidu.com\n"); strcat (str1, "\ n"); printf ("%s", str1); ret = Write (Sockfd,str1,strlen (str1)); if (Ret < 0) {printf ("errno =%d strerror =%s\n", errno, Strerror (errno)); Exit (0); }else{printf ("Send%d size\n", ret); } fd_zero (&T_SET1); Fd_set (SOCKFD, &t_set1); while (1) { Tv.tv_sec= 2; tv.tv_usec= 0; H= 0; printf ("--------------->1\n"); H= Select (sockfd +1, &t_set1, NULL, NULL, &TV); printf ("--------------->2\n"); printf ("H ===================%d\n", h); if (h = = 0) continue; if (H < 0) {close (SOCKFD);p rintf ("Select Error \ n"); return-1; } if (H > 0) {memset (buf, 0, BUFSIZE); I= Read (SOCKFD, buf, BUFSIZE-1); I= Read (SOCKFD, buf, BUFSIZE-1);p rintf ("I ==========================%d", i); if (i==0) {close (SOCKFD);p rintf ("Stop ... ... \ n");); return-1; } printf ("%s\n", buf); }} close (SOCKFD); return 0;}
Explanation of use of Linux C select function