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