c++ socket 发送HTTP请求
#include <iostream>;
using namespace std;
#include <sys/types.h>;
#include <sys/stat.h>;
#include <fcntl.h>;
#include <sys/socket.h>;
#include <sys/stat.h>;
#include <unistd.h>;
#include <stdlib.h>;
#include <netdb.h>;
#include <arpa/inet.h>;
#include <netinet/in.h>;
#include <string.h>;
#include <errno.h>;
int main(int argc, char* argv[])
{
if (argc != 3) {
cout << "useage: " << argv[0] << " <ipaddress>;" << " <port>;" << endl;
cout << "errno= " << errno << endl;
exit(1);
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
cout << "Can not create socket!" << endl;
cout << "errno= " << errno << endl;
exit(2);
}
struct sockaddr_in cliaddr;
int len = sizeof(cliaddr);
memset(&cliaddr, 0, len);
cliaddr.sin_family = AF_INET;
cliaddr.sin_addr.s_addr = inet_addr(argv[1]);
cliaddr.sin_port = htons(atoi(argv[2]));
if((connect(sockfd, (sockaddr*)&cliaddr, len)) < 0) {
cout << "Can not create connect!" << endl;
cout << "errno= " << errno << endl;
exit(3);
}
char buf[2048];
strcpy(buf, "GET / HTTP/1.0 \r\n\r\n");
if (write(sockfd, buf, strlen(buf)) < 0) {
cout << "Write error!" << endl;
cout << "errno= " << endl;
exit(4);
}
memset(buf, 0, 2048);
if (read(sockfd, buf, 2048) < 0) {
cout << "Read error!" << endl;
cout << "errno= " << endl;
exit(5);
}
int ok = open("test.html", O_WRONLY|O_CREAT, 0777);
if (ok < 0) {
cout << "Can not open test.html, please try again!" << endl;
cout << "errno= " << errno << endl;
exit(6);
}
if (write(ok, buf, strlen(buf)) < 0) {
cout << "Write error!" << endl;
cout << "errno= " << endl;
exit(7);
}
cout << buf << endl;
close(sockfd);
close(ok);
}