#include #include #include #include #include #include #include #include int skt; // Global. This is the socket that the server will listen on struct character{ char type; char name[32]; char flags; uint16_t attack; uint16_t defense; uint16_t regen; int16_t health; uint16_t gold; uint16_t room; uint16_t description_length; } __attribute__((packed)); void close_server(int signal_number){ printf("Closing down the server\n"); close(skt); } int main(int argc, char ** argv){ struct sockaddr_in sad; sad.sin_port = htons(5141); sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; skt = socket(AF_INET, SOCK_STREAM, 0); if(skt == -1){ perror("socket"); return 1; } struct sigaction close_action; close_action.sa_handler = close_server; if(sigaction(SIGINT, &close_action, 0)){ perror("sigaction"); return 1; } if( bind(skt, (struct sockaddr *)(&sad), sizeof(struct sockaddr_in)) ){ perror("bind"); return 1; } if( listen(skt, 5) ){ perror("listen"); return 1; } int client_fd; struct sockaddr_in client_address; socklen_t address_size = sizeof(struct sockaddr_in); for(;;){ client_fd = accept(skt, (struct sockaddr *)(&client_address), &address_size); if(client_fd == -1){ perror("accept"); break; } printf("Connection made from address %s\n", inet_ntoa(client_address.sin_addr)); char version[5]; version[0] = 14; version[1] = 6; version[2] = 3; version[3] = 0; version[4] = 0; write(client_fd, version, 5); char game[1024]; char *description = "This is a game about moose. The moose like to hide in caves and attack the player!"; game[0] = 11; *((unsigned short*)(game+1)) = 3000; *((unsigned short*)(game+3)) = 8192; *((unsigned short*)(game+5)) = strlen(description); strcpy(game+7, description); write(client_fd, game, 7 + strlen(description)); struct character trudy = {10, "Trudy", 0, 100, 357, 1000, 100, 0, 3, 0}; char *trudy_description = "Notorious network intruder"; trudy.description_length = strlen(trudy_description); write(client_fd, &trudy, sizeof(trudy)); write(client_fd, trudy_description, trudy.description_length); close(client_fd); } return 0; }