InetAddress.cc revision 65c497a3
165c497a3SShuo Chen// Copyright 2010, Shuo Chen.  All rights reserved.
265c497a3SShuo Chen// http://code.google.com/p/muduo/
365c497a3SShuo Chen//
465c497a3SShuo Chen// Use of this source code is governed by a BSD-style license
565c497a3SShuo Chen// that can be found in the License file.
665c497a3SShuo Chen
765c497a3SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
865c497a3SShuo Chen
965c497a3SShuo Chen#include "InetAddress.h"
1065c497a3SShuo Chen
1165c497a3SShuo Chen#include "SocketsOps.h"
1265c497a3SShuo Chen
1365c497a3SShuo Chen#include <strings.h>  // bzero
1465c497a3SShuo Chen#include <netinet/in.h>
1565c497a3SShuo Chen
1665c497a3SShuo Chen#include <boost/static_assert.hpp>
1765c497a3SShuo Chen
1865c497a3SShuo Chen//     /* Structure describing an Internet socket address.  */
1965c497a3SShuo Chen//     struct sockaddr_in {
2065c497a3SShuo Chen//         sa_family_t    sin_family; /* address family: AF_INET */
2165c497a3SShuo Chen//         uint16_t       sin_port;   /* port in network byte order */
2265c497a3SShuo Chen//         struct in_addr sin_addr;   /* internet address */
2365c497a3SShuo Chen//     };
2465c497a3SShuo Chen
2565c497a3SShuo Chen//     /* Internet address. */
2665c497a3SShuo Chen//     typedef uint32_t in_addr_t;
2765c497a3SShuo Chen//     struct in_addr {
2865c497a3SShuo Chen//         in_addr_t       s_addr;     /* address in network byte order */
2965c497a3SShuo Chen//     };
3065c497a3SShuo Chen
3165c497a3SShuo Chenusing namespace muduo;
3265c497a3SShuo Chenusing std::string;
3365c497a3SShuo Chen
3465c497a3SShuo Chenstatic const in_addr_t kInaddrAny = INADDR_ANY;
3565c497a3SShuo Chen
3665c497a3SShuo ChenBOOST_STATIC_ASSERT(sizeof(InetAddress) == sizeof(struct sockaddr_in));
3765c497a3SShuo Chen
3865c497a3SShuo ChenInetAddress::InetAddress(uint16_t port)
3965c497a3SShuo Chen{
4065c497a3SShuo Chen  bzero(&addr_, sizeof addr_);
4165c497a3SShuo Chen  addr_.sin_family = AF_INET;
4265c497a3SShuo Chen  addr_.sin_addr.s_addr = sockets::hostToNetwork32(kInaddrAny);
4365c497a3SShuo Chen  addr_.sin_port = sockets::hostToNetwork16(port);
4465c497a3SShuo Chen}
4565c497a3SShuo Chen
4665c497a3SShuo ChenInetAddress::InetAddress(const string& ip, uint16_t port)
4765c497a3SShuo Chen{
4865c497a3SShuo Chen  bzero(&addr_, sizeof addr_);
4965c497a3SShuo Chen  sockets::fromHostPort(ip.c_str(), port, &addr_);
5065c497a3SShuo Chen}
5165c497a3SShuo Chen
5265c497a3SShuo Chenstring InetAddress::toHostPort() const
5365c497a3SShuo Chen{
5465c497a3SShuo Chen  char buf[32];
5565c497a3SShuo Chen  sockets::toHostPort(buf, sizeof buf, addr_);
5665c497a3SShuo Chen  return buf;
5765c497a3SShuo Chen}
5865c497a3SShuo Chen
59