ipv4addr.cpp

Go to the documentation of this file.
00001 /*
00002  *  Copyright (C) 2004-2005 Alo Sarv <madcat_@users.sourceforge.net>
00003  *
00004  *  This program is free software; you can redistribute it and/or modify
00005  *  it under the terms of the GNU General Public License as published by
00006  *  the Free Software Foundation; either version 2 of the License, or
00007  *  (at your option) any later version.
00008  *
00009  *  This program is distributed in the hope that it will be useful,
00010  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  *  GNU General Public License for more details.
00013  *
00014  *  You should have received a copy of the GNU General Public License
00015  *  along with this program; if not, write to the Free Software
00016  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00017  */
00018 
00019 /** @file ipv4addr.cpp Implementation of IPV4Addr class */
00020 
00021 #include <hn/hnprec.h>
00022 #include <hn/ipv4addr.h>
00023 #include <boost/lexical_cast.hpp>
00024 
00025 #ifdef WIN32
00026         #include <winsock2.h>
00027 #else
00028         #include <netinet/in.h>
00029         #include <arpa/inet.h>
00030 #endif
00031 
00032 namespace Socket {
00033         //! make internet address
00034         uint32_t makeAddr(const std::string &addr) {
00035                 return inet_addr(addr.c_str());
00036         }
00037         std::string getAddr(uint32_t ip) {
00038                 return inet_ntoa(*(in_addr*)&ip);
00039         }
00040 }
00041 
00042 // IPV4Address class
00043 // -----------------
00044 
00045 IPV4Address::IPV4Address() : m_addr(), m_port() {}
00046 IPV4Address::IPV4Address(const std::string &addr, uint16_t port /* = 0 */)
00047 : m_addr(Socket::makeAddr(addr)), m_port(port) {}
00048 
00049 IPV4Address::IPV4Address(uint32_t addr, uint16_t port /* = 0 */)
00050 : m_addr(addr), m_port(port) {}
00051 
00052 std::ostream& operator<<(std::ostream &o, const IPV4Address &a) {
00053         return o << a.getStr();
00054 }
00055 
00056 std::string IPV4Address::getStr() const {
00057         std::string ret(Socket::getAddr(m_addr));
00058         if (m_port) {
00059                 ret += ":";
00060                 ret += boost::lexical_cast<std::string>(m_port);
00061         }
00062         return ret;
00063 }
00064 
00065 std::string IPV4Address::getAddrStr() const {
00066         return Socket::getAddr(m_addr);
00067 }
00068 
00069 void IPV4Address::setAddr(const std::string &addr) {
00070         m_addr = Socket::makeAddr(addr);
00071 }