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