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