// server_socket.cc // robert - programme du robot 2005. {{{ // // Copyright (C) 2005 Dufour Jérémy // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Contact : // Web: %WEB% // Email: // }}} #include "server_socket.hh" #include "address.hh" #include #include #include /// Constructeur par défaut. ServerSocket::ServerSocket (int port) { bind (port); } /// Bind le serveur sur un port d'écoute. void ServerSocket::bind (int port) { static const int reuse_s = 1; // Adresse sur un port (pas d'hote, écoutera de partout) Address a (port); // Création du socket IPv4 - TCP socket_ = socket (PF_INET, SOCK_STREAM, 0); if (socket_ == -1) throw std::runtime_error ("Erreur de création du socket"); // Socket réutilisable en cas d'arret "brutale" if (setsockopt (socket_, SOL_SOCKET, SO_REUSEADDR, &reuse_s, sizeof (int)) == -1) throw std::runtime_error ("Erreur setsockopt : reusable"); // Bindage du socket sur le port et l'adresse if (::bind (socket_, a.getSockaddr (), sizeof (struct sockaddr_in)) == -1) throw std::runtime_error ("Erreur de bind du socket"); // On met le socket en attente de connexion if (listen (socket_, 0) == -1) throw std::runtime_error ("Erreur de listen"); } // Accepte une nouvelle connexion. int ServerSocket::accept (void) const { int s = ::accept (socket_, 0, 0); if (s == -1) throw std::runtime_error ("Erreur d'accept de nouvelles connexions"); return s; } // Accepte une nouvelle connexion et remplie Address. int ServerSocket::accept (Address &a) const { sockaddr_in sa; socklen_t sl = sizeof sa; int s = ::accept (socket_, reinterpret_cast (&sa), &sl); if (s == -1) { throw std::runtime_error ("Erreur d'accept nouvelle connexion"); } // Récupération de l'adresse a = Address (reinterpret_cast (&sa), sl); return s; }