#include "Networking/sockets.h" #include "Networking/ServerSocket.h" #include "Networking/Server.h" #include #include #include /* * Get the client ip number on the socket connection for client i. */ void Server::get_ip(int num) { struct sockaddr_storage addr; socklen_t len = sizeof addr; getpeername(socket_num[num], (struct sockaddr*)&addr, &len); // supports both IPv4 and IPv6: char ipstr[INET6_ADDRSTRLEN]; if (addr.ss_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in *)&addr; inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr); } else { // AF_INET6 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr; inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr); } names[num]=new octet[512]; memset(names[num], 0, 512); strncpy((char*)names[num], ipstr, INET6_ADDRSTRLEN); #ifdef DEBUG_NETWORKING cerr << "Client IP address: " << names[num] << endl; #endif } void Server::get_name(int num) { // Now all machines are set up, send GO to start them. send(socket_num[num], GO); #ifdef DEBUG_NETWORKING cerr << "Player " << num << " started." << endl; #endif // Receive name sent by client (legacy) - not used here octet my_name[512]; receive(socket_num[num],my_name,512); receive(socket_num[num],(octet*)&ports[num],4); #ifdef DEBUG_NETWORKING cerr << "Player " << num << " sent (IP for info only) " << my_name << ":" << ports[num] << endl; #endif // Get client IP get_ip(num); } void Server::send_names(int num) { /* Now send the machine names back to each client * and the number of machines */ send(socket_num[num],nmachines); for (int i=0; istart(); pthread_detach(pthread_self()); return 0; } Server* Server::start_networking(Names& N, int my_num, int nplayers, string hostname, int portnum) { #ifdef DEBUG_NETWORKING cerr << "Starting networking for " << my_num << "/" << nplayers << " with server on " << hostname << ":" << (portnum - 1) << endl; #endif assert(my_num >= 0); assert(my_num < nplayers); Server* server = 0; if (my_num == 0) { pthread_t thread; pthread_create(&thread, 0, Server::start_in_thread, server = new Server(nplayers, portnum)); } N.init(my_num, portnum, Names::DEFAULT_PORT, hostname.c_str()); return server; }