1 #include "network_controller.h"
3 NetworkController::NetworkController(const Piece::Colour & newColour, const char * newName) : Controller(newColour, newName), sfd(-1)
5 struct protoent * tcp = getprotobyname("tcp");
7 sfd = socket(PF_INET, SOCK_STREAM, tcp->p_proto);
10 // fprintf(stderr, "NetworkController::NetworkController - couldn't create a TCP socket!");
11 perror("NetworkController::NetworkController - creating TCP socket... ");
16 NetworkController::~NetworkController()
20 if (shutdown(sfd, SHUT_RDWR) == -1)
22 // fprintf(stderr, "NetworkController::~NetworkController - Can't shutdown socket %d!", sfd);
23 perror("NetworkController::~NetworkController - shutting down socket... ");
31 Server::Server(const Piece::Colour & newColour, const char * newName) : NetworkController(newColour, newName)
33 struct sockaddr_in ipa;
34 ipa.sin_family = AF_INET;
35 ipa.sin_port = htons(NetworkController::port);
36 ipa.sin_addr.s_addr = INADDR_ANY;
37 memset(&ipa,0, sizeof ipa);
39 if (bind(sfd, (struct sockaddr*)&ipa, sizeof (ipa)) == -1) //dERP DERP DERP
41 // fprintf(stderr, "Server::Server - Couldn't bind to socket! Abort\n");
42 perror("Server::Server - binding to socket... ");
48 //Listen for at most 1 connection
49 if (listen(sfd, 1) == -1)
51 fprintf(stderr, "Server::Server - listening failed.\n");
57 //Accept the connection
58 sfd = accept(sfd, NULL, NULL);
61 fprintf(stderr, "Server::Server - couldn't accept connection.\n");
67 //We are now ready to play!
71 Client::Client(const Piece::Colour & newColour, const char * newName, const char * server) : NetworkController(newColour, newName)
73 struct sockaddr_in ipa;
74 ipa.sin_family = AF_INET;
75 ipa.sin_port = htons(NetworkController::port);
76 int Res = inet_pton(AF_INET, server, &ipa.sin_addr);
80 fprintf(stderr, "Client::Client - First parameter is not a valid address family!\n");
87 fprintf(stderr, "Client::Client - Second parameter does not contain a valid IP Address!\n");
93 if (connect(sfd, (struct sockaddr*)&sfd, sizeof sfd) == -1)
95 fprintf(stderr, "Client::Client - Connection to server at \"%s\" failed.\n", server);
101 //We are now ready to play!