InetAddress.cc revision 354280cf
1354280cfSShuo Chen// Copyright 2010, Shuo Chen.  All rights reserved.
2354280cfSShuo Chen// http://code.google.com/p/muduo/
3354280cfSShuo Chen//
4354280cfSShuo Chen// Use of this source code is governed by a BSD-style license
5354280cfSShuo Chen// that can be found in the License file.
6354280cfSShuo Chen
7354280cfSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
8354280cfSShuo Chen
9354280cfSShuo Chen#include "InetAddress.h"
10354280cfSShuo Chen
11354280cfSShuo Chen#include "SocketsOps.h"
12354280cfSShuo Chen
13354280cfSShuo Chen#include <strings.h>  // bzero
14354280cfSShuo Chen#include <netinet/in.h>
15354280cfSShuo Chen
16354280cfSShuo Chen#include <boost/static_assert.hpp>
17354280cfSShuo Chen
18354280cfSShuo Chen//     /* Structure describing an Internet socket address.  */
19354280cfSShuo Chen//     struct sockaddr_in {
20354280cfSShuo Chen//         sa_family_t    sin_family; /* address family: AF_INET */
21354280cfSShuo Chen//         uint16_t       sin_port;   /* port in network byte order */
22354280cfSShuo Chen//         struct in_addr sin_addr;   /* internet address */
23354280cfSShuo Chen//     };
24354280cfSShuo Chen
25354280cfSShuo Chen//     /* Internet address. */
26354280cfSShuo Chen//     typedef uint32_t in_addr_t;
27354280cfSShuo Chen//     struct in_addr {
28354280cfSShuo Chen//         in_addr_t       s_addr;     /* address in network byte order */
29354280cfSShuo Chen//     };
30354280cfSShuo Chen
31354280cfSShuo Chenusing namespace muduo;
32354280cfSShuo Chen
33354280cfSShuo Chenstatic const in_addr_t kInaddrAny = INADDR_ANY;
34354280cfSShuo Chen
35354280cfSShuo ChenBOOST_STATIC_ASSERT(sizeof(InetAddress) == sizeof(struct sockaddr_in));
36354280cfSShuo Chen
37354280cfSShuo ChenInetAddress::InetAddress(uint16_t port)
38354280cfSShuo Chen{
39354280cfSShuo Chen  bzero(&addr_, sizeof addr_);
40354280cfSShuo Chen  addr_.sin_family = AF_INET;
41354280cfSShuo Chen  addr_.sin_addr.s_addr = sockets::hostToNetwork32(kInaddrAny);
42354280cfSShuo Chen  addr_.sin_port = sockets::hostToNetwork16(port);
43354280cfSShuo Chen}
44354280cfSShuo Chen
45354280cfSShuo ChenInetAddress::InetAddress(const std::string& ip, uint16_t port)
46354280cfSShuo Chen{
47354280cfSShuo Chen  bzero(&addr_, sizeof addr_);
48354280cfSShuo Chen  sockets::fromHostPort(ip.c_str(), port, &addr_);
49354280cfSShuo Chen}
50354280cfSShuo Chen
51354280cfSShuo Chenstd::string InetAddress::toHostPort() const
52354280cfSShuo Chen{
53354280cfSShuo Chen  char buf[32];
54354280cfSShuo Chen  sockets::toHostPort(buf, sizeof buf, addr_);
55354280cfSShuo Chen  return buf;
56354280cfSShuo Chen}
57354280cfSShuo Chen
58