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