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