Работа с сокетами на C++
Этот простой пример скачивает главную страницу CodeNet.ru.
#include <cstring> #include <stdlib.h> #include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <string.h> #include <assert.h> #include <stdio.h> #include <sstream> char var[]={"http://www.codenet.ru/"}; std::string m = "GET / HTTP/1.1\r\nHost: "; std::string s="\r\n" "User-Agent: Mozilla/5.0\r\n" "Accept: text/html\r\n" "Accept-Language: ru,en-us;q=0.7,en;q=0.3\r\n" "Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7\r\n" "Connection: keep-alive\r\n\r\n"; char message[999]; char buf[1]; int main(int argc, char* argv[]) { std::stringstream conv; conv<<m<<var<<s; conv.read(message,999); std::cout<<message<<std::endl<<std::endl; int sock; struct sockaddr_in addr; struct hostent* raw_host; raw_host = gethostbyname(var); if (raw_host == NULL) { std::cout<<"ERROR, no such host"; exit(0); } sock = socket(AF_INET, SOCK_STREAM, 0); addr.sin_family = AF_INET; addr.sin_port = htons(80); bcopy((char *)raw_host->h_addr,(char *)&addr.sin_addr, raw_host->h_length); if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { std::cerr<<"connect error"<<std::endl; exit(2); } send(sock, message, sizeof(message), 0); recv(sock, buf, sizeof(buf), 0); std::cout<<buf; while(buf) { buf[0]=NULL; recv(sock, buf, sizeof(buf), 0); std::cout<<buf; } return (EXIT_SUCCESS); }