I have a program which splits a url into host and path:
int main(int argc, char** argv){
std::vector<std::string> url = parseUrl(argv[1]);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int MAXDATASIZE = 1024;
std::string request = "GET " +url.at(1) + " HTTP/1.1\r\n\r\n";
const char* charRequest = request.c_str();
char buf[MAXDATASIZE];
if((status = getaddrinfo(url.at(0).c_str(), "80", &hints, &servinfo)) != 0){
std::cout << "getaddrinfo: " << gai_strerror(status) << "\n";
return 2;
} else {
std::cout << "Server struct created successfully\n";
}
if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1){
std::cout << "Error creating socket\n";
return 2;
} else {
std::cout << "Successfully created socket\n";
}
if(connect(sock, servinfo->ai_addr, servinfo->ai_addrlen) == -1){
std::cout << "Error connecting to host " << url.at(0) << " at port " << "80" << "\n";
return 2;
} else {
std::cout << "Connected successfully to " << url.at(0) << "at port " << "80" << "\n";
}
if((send(sock, charRequest, strlen(charRequest), 0)) == -1){
std::cout << "Error communicating with website\n";
return 2;
} else {
std::cout << "Sent request successfully to " << url.at(0) << " at port " << "80" << "\n";
}
if(recv(sock, buf, MAXDATASIZE, 0) == -1){
std::cout << "Error recciving data from " << url.at(0) << " at port " << "80" << "\n";
} else {
std::cout << "Recieved data successfully from " << url.at(0) << " at port " << "80" << "\n";
}
std::ofstream file;
file.open(argv[2]);
file << buf;
file.close();
close(sock);
freeaddrinfo(servinfo);
}
// Returns vector with host as first argument and path as second
std::vector<std::string> parseUrl(std::string url){
std::vector<std::string> ret;
size_t dotPos = url.find('.');
size_t slashPos = url.find('/', dotPos);
std::string host = url.substr(0, slashPos);
std::string path = url.substr(slashPos, url.length());
ret.push_back(host);
ret.push_back(path);
return ret;
}
Does anyone have suggestions for improvement. Especially about the clunky vector return?
moved
back avoiding any copies. \$\endgroup\$dot
in it. See: en.wikipedia.org/wiki/URL. This image I find particularly helpful: en.wikipedia.org/wiki/File:URI_syntax_diagram.svg but the full definition is here: tools.ietf.org/html/rfc3986 \$\endgroup\$schema
,user
,host
,port
,path
,query
, fragment` (removing the dividers). Not in the wild a lot of URL are mall formed most browser take this into account. The worst offenders is not having the?
before the query. \$\endgroup\$