Send to http server request SUCCESS!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#define MAXRECV 1024
int main() {
sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(80);
my_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int my_sock = socket(AF_INET, SOCK_STREAM, 0);
int result = connect(my_sock, (sockaddr*)&my_addr, sizeof(sockaddr));
if (result < 0) {
perror("can not connect to socket");
}
const char *msg = "GET / HTTP/1.1\nHost: localhost\n\n";
send(my_sock, msg, strlen(msg), 0);
char buf[MAXRECV + 1];
int n = recv(my_sock, buf, MAXRECV, 0);
std::cout<<buf<<std::endl;
close(my_sock);
return 0;
}