1e254a845SShuo Chen// Copyright 2010, Shuo Chen.  All rights reserved.
2e254a845SShuo Chen// http://code.google.com/p/muduo/
3e254a845SShuo Chen//
4e254a845SShuo Chen// Use of this source code is governed by a BSD-style license
5e254a845SShuo Chen// that can be found in the License file.
6e254a845SShuo Chen
7e254a845SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
8e254a845SShuo Chen
9e254a845SShuo Chen#include "InetAddress.h"
10e254a845SShuo Chen
11e254a845SShuo Chen#include "SocketsOps.h"
12e254a845SShuo Chen
13e254a845SShuo Chen#include <strings.h>  // bzero
14e254a845SShuo Chen#include <netinet/in.h>
15e254a845SShuo Chen
16e254a845SShuo Chen#include <boost/static_assert.hpp>
17e254a845SShuo Chen
18e254a845SShuo Chen//     /* Structure describing an Internet socket address.  */
19e254a845SShuo Chen//     struct sockaddr_in {
20e254a845SShuo Chen//         sa_family_t    sin_family; /* address family: AF_INET */
21e254a845SShuo Chen//         uint16_t       sin_port;   /* port in network byte order */
22e254a845SShuo Chen//         struct in_addr sin_addr;   /* internet address */
23e254a845SShuo Chen//     };
24e254a845SShuo Chen
25e254a845SShuo Chen//     /* Internet address. */
26e254a845SShuo Chen//     typedef uint32_t in_addr_t;
27e254a845SShuo Chen//     struct in_addr {
28e254a845SShuo Chen//         in_addr_t       s_addr;     /* address in network byte order */
29e254a845SShuo Chen//     };
30e254a845SShuo Chen
31e254a845SShuo Chenusing namespace muduo;
32e254a845SShuo Chen
33e254a845SShuo Chenstatic const in_addr_t kInaddrAny = INADDR_ANY;
34e254a845SShuo Chen
35e254a845SShuo ChenBOOST_STATIC_ASSERT(sizeof(InetAddress) == sizeof(struct sockaddr_in));
36e254a845SShuo Chen
37e254a845SShuo ChenInetAddress::InetAddress(uint16_t port)
38e254a845SShuo Chen{
39e254a845SShuo Chen  bzero(&addr_, sizeof addr_);
40e254a845SShuo Chen  addr_.sin_family = AF_INET;
41e254a845SShuo Chen  addr_.sin_addr.s_addr = sockets::hostToNetwork32(kInaddrAny);
42e254a845SShuo Chen  addr_.sin_port = sockets::hostToNetwork16(port);
43e254a845SShuo Chen}
44e254a845SShuo Chen
45e254a845SShuo ChenInetAddress::InetAddress(const std::string& ip, uint16_t port)
46e254a845SShuo Chen{
47e254a845SShuo Chen  bzero(&addr_, sizeof addr_);
48e254a845SShuo Chen  sockets::fromHostPort(ip.c_str(), port, &addr_);
49e254a845SShuo Chen}
50e254a845SShuo Chen
51e254a845SShuo Chenstd::string InetAddress::toHostPort() const
52e254a845SShuo Chen{
53e254a845SShuo Chen  char buf[32];
54e254a845SShuo Chen  sockets::toHostPort(buf, sizeof buf, addr_);
55e254a845SShuo Chen  return buf;
56e254a845SShuo Chen}
57e254a845SShuo Chen
58