// address.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 "address.hh" #include #include /// Constructeur par défaut. Address::Address (void) : port_ (0) { resolv (); } /// Constructeur avec le port (serveur) Address::Address (const int port) : port_ (port) { resolv (); } /// Constructeur avec hôte et port. Address::Address (const std::string &host, const int port) : host_ (host), port_ (port) { resolv (); } /// Constructeur à partir de la strcuture d'adresse. Address::Address (const sockaddr *sa, socklen_t sl) { // On vérifie que c'est vraiment un struct sockaddr_in if (sl != sizeof (sockaddr_in)) throw std::invalid_argument ("Invalide Adresse"); sa_ = * reinterpret_cast (sa); } /// Résolution de la structure d'adresse depuis l'hôte/port void Address::resolv (void) { // Cas du serveur, pas d'hôte if (host_.empty ()) sa_.sin_addr.s_addr = htonl (INADDR_ANY); else { // Convertion de l'hôte en structure adresse if (!inet_pton (AF_INET, host_.c_str (), &sa_.sin_addr)) { hostent *host_info = gethostbyname (host_.c_str ()); if (!host_info) throw std::runtime_error (host_ + " : Hôte inconnue"); } } sa_.sin_family = AF_INET; // Convertion pour le passage sur le réseau sa_.sin_port = htons (port_); } /// Résolution de l'hôte/port depuis la structure d'adresse void Address::unresolv (void) { hostent *host_info; // Recherche de l'hôte host_info = gethostbyaddr (reinterpret_cast (&(sa_.sin_addr)), sizeof sa_.sin_addr, AF_INET); if (!host_info) host_ = inet_ntoa (sa_.sin_addr); else host_ = host_info->h_name; // Recherche du port port_ = ntohs (sa_.sin_port); }