#include #include #include #include #include #include #include #include #include #include using namespace std; bool authenticate(int fd){ char buffer[20]; read(fd, buffer, 200); // char *newline = strchr(buffer, '\n'); // if(newline) // *newline = 0; if(!strcmp(buffer, "gerbil")){ return true; } else { // printf("Invalid Password: \"%s\"\n", buffer); return false; } } int main(int argc, char ** argv){ uint16_t port = 5143; struct sockaddr_in sad; sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; top: sad.sin_port = htons(port); int skt = socket(AF_INET, SOCK_STREAM, 0); // Step 1 if(skt == -1){ perror("socket"); return 1; } if( bind(skt, (struct sockaddr*)(&sad), sizeof(struct sockaddr_in)) ){ // step 2 port++; goto top; } if( listen(skt, 5) ){ // step 3 perror("listen"); return 1; } printf("Listening on port %d\n", port); while(1){ int client_fd; struct sockaddr_in client_address; socklen_t address_size = sizeof(struct sockaddr_in); client_fd = accept(skt, (struct sockaddr *)(&client_address), &address_size); // step 4 if(authenticate(client_fd)){ printf("Client successfully authenticated\n"); write(client_fd, "We trust you", 12); } close(client_fd); } return 0; }