Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int init(int port) {
- /**
- * This function initialises the server
- * It creates the initial sock, binds
- * and then listens on the defined port
- * Returns: Socket Descriptor (INT)
- */
- int httpd;
- struct sockaddr_in mySockAddr, remoteAddr;
- socklen_t remoteAddr_len;
- mySockAddr.sin_family = AF_INET;
- mySockAddr.sin_port = htons(port);
- cout << "Initialising Server...";
- logEvent(1, "[NOTICE] Initialising Server...", false);
- httpd = socket(AF_INET, SOCK_STREAM, 0);
- inet_aton("127.0.0.1", &mySockAddr.sin_addr);
- if(httpd == -1){
- logEvent(1,("[ERROR] Creating Socket failed."));
- }
- if(bind(httpd,(struct sockaddr*) &mySockAddr, sizeof(mySockAddr)) < 0) {
- cout << errno << endl;
- logEvent(1,("[ERROR] Binding on port "+convertInt(port)+" failed."));
- }
- if(listen(httpd, MAX_CLIENTS) == -1) {
- logEvent(1,("[ERROR] listening on port "+convertInt(port)+" failed."));
- } else {
- cout << "\t[OK]" << endl;
- logEvent(1, ("[NOTICE] Server started on port "+convertInt(port)), false);
- }
- return httpd;
- }
- int handle_connection(int ClientSocket) {
- socklen_t len;
- struct sockaddr_storage addr;
- char ipstr[INET6_ADDRSTRLEN];
- int port;
- const char* buf;
- const char* body;
- len = sizeof addr;
- getpeername(ClientSocket, (struct sockaddr*)&addr, &len);
- // deal with both IPv4 and IPv6:
- if (addr.ss_family == AF_INET) {
- struct sockaddr_in *ClientSocket = (struct sockaddr_in *)&addr;
- port = ntohs(ClientSocket->sin_port);
- inet_ntop(AF_INET, &ClientSocket->sin_addr, ipstr, sizeof ipstr);
- }
- string IP;
- IP.assign(ipstr);
- logEvent(1, ("Connection Established with: "+IP));
- buf = "HTTP/1.0 200 OK\r\n";
- send(ClientSocket, buf, strlen(buf), 0);
- buf = "Server: eoPanel Server\r\n";
- send(ClientSocket, buf, strlen(buf), 0);
- buf = "Content-Type: text/html; charset=UTF-8\r\n";
- send(ClientSocket, buf, strlen(buf), 0);
- buf = "Content-Length: 20\r\n";
- send(ClientSocket, buf, strlen(buf), 0);
- buf = "\r\n";
- send(ClientSocket, buf, strlen(buf), 0);
- body = "<h2> Welcome </h2>";
- send(ClientSocket, body, strlen(body), 0);
- close(ClientSocket);
- }
- string convertInt(int number){
- stringstream ss;//create a stringstream
- ss << number;//add number to the stream
- return ss.str();//return a string with the contents of the stream
- }
- int main(int argc, char* argv[]) {
- int port;
- struct sockaddr_in remoteAddr;
- socklen_t remoteAddr_len;
- if(argv[1] > 0) {
- port = atoi(argv[1]);
- } else {
- port = DEFAULT_PORT;
- }
- ServerSocket = init(port);
- if(ServerSocket == -1) {
- logEvent(1,("[ERROR] Main did not receive a correct socketID from init();"));
- exit(1);
- }
- while(1) {
- ClientSocket = accept(ServerSocket, (struct sockaddr*) &remoteAddr, &remoteAddr_len);
- handle_connection(ClientSocket);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement