summaryrefslogtreecommitdiff
path: root/i/simulotron/src/socket/address.cc
blob: 4567e2ee144fae51df9a06946c646c99e0390135 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// 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: <dufourj@efrei.fr>
// }}}
#include "address.hh"

#include <netdb.h>
#include <stdexcept>

/// 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<const sockaddr_in*> (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<char *> (&(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);
}