Files
shadowrun-server/src/utils.cpp

79 lines
1.8 KiB
C++

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "utils.hpp"
#include <algorithm>
#include <fstream>
#include <sstream>
using namespace std;
namespace utils {
expected<bool, string> isLocalPortOpen(uint16_t portno) {
const char *hostname = "localhost";
int sockfd;
bool ret;
struct sockaddr_in serv_addr;
struct hostent *server;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
close(sockfd);
return unexpected("ERROR opening socket");
}
server = gethostbyname(hostname);
if (server == NULL) {
close(sockfd);
return unexpected("ERROR, no such host");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
ret = false;
} else {
ret = true;
}
close(sockfd);
return ret;
}
string to_id_format(const string& s){
string new_s = s;
// transform(new_s.begin(), new_s.end(), new_s.begin(),
// [](unsigned char c){ return std::tolower(c); });
replace( new_s.begin(), new_s.end(), ' ', '-');
return new_s;
}
string loadFile(const string& path) {
ifstream f(path);
stringstream buffer;
buffer << f.rdbuf();
return buffer.str();
}
std::filesystem::path getDataDir(){
return std::getenv("XDG_DATA_HOME")
? std::filesystem::path(std::getenv("XDG_DATA_HOME")) / APPLICATION_NAME
: std::filesystem::path(std::getenv("HOME")) / ".local" / "share" / APPLICATION_NAME;
}
}