12a18e699SShuo Chen// Copyright 2010, Shuo Chen. All rights reserved. 22a18e699SShuo Chen// http://code.google.com/p/muduo/ 32a18e699SShuo Chen// 42a18e699SShuo Chen// Use of this source code is governed by a BSD-style license 52a18e699SShuo Chen// that can be found in the License file. 62a18e699SShuo Chen 72a18e699SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 82a18e699SShuo Chen 92a18e699SShuo Chen#include "InetAddress.h" 102a18e699SShuo Chen 112a18e699SShuo Chen#include "SocketsOps.h" 122a18e699SShuo Chen 132a18e699SShuo Chen#include <strings.h> // bzero 142a18e699SShuo Chen#include <netinet/in.h> 152a18e699SShuo Chen 162a18e699SShuo Chen#include <boost/static_assert.hpp> 172a18e699SShuo Chen 182a18e699SShuo Chen// /* Structure describing an Internet socket address. */ 192a18e699SShuo Chen// struct sockaddr_in { 202a18e699SShuo Chen// sa_family_t sin_family; /* address family: AF_INET */ 212a18e699SShuo Chen// uint16_t sin_port; /* port in network byte order */ 222a18e699SShuo Chen// struct in_addr sin_addr; /* internet address */ 232a18e699SShuo Chen// }; 242a18e699SShuo Chen 252a18e699SShuo Chen// /* Internet address. */ 262a18e699SShuo Chen// typedef uint32_t in_addr_t; 272a18e699SShuo Chen// struct in_addr { 282a18e699SShuo Chen// in_addr_t s_addr; /* address in network byte order */ 292a18e699SShuo Chen// }; 302a18e699SShuo Chen 312a18e699SShuo Chenusing namespace muduo; 322a18e699SShuo Chen 332a18e699SShuo Chenstatic const in_addr_t kInaddrAny = INADDR_ANY; 342a18e699SShuo Chen 352a18e699SShuo ChenBOOST_STATIC_ASSERT(sizeof(InetAddress) == sizeof(struct sockaddr_in)); 362a18e699SShuo Chen 372a18e699SShuo ChenInetAddress::InetAddress(uint16_t port) 382a18e699SShuo Chen{ 392a18e699SShuo Chen bzero(&addr_, sizeof addr_); 402a18e699SShuo Chen addr_.sin_family = AF_INET; 412a18e699SShuo Chen addr_.sin_addr.s_addr = sockets::hostToNetwork32(kInaddrAny); 422a18e699SShuo Chen addr_.sin_port = sockets::hostToNetwork16(port); 432a18e699SShuo Chen} 442a18e699SShuo Chen 45b4a5ce52SShuo ChenInetAddress::InetAddress(const std::string& ip, uint16_t port) 462a18e699SShuo Chen{ 472a18e699SShuo Chen bzero(&addr_, sizeof addr_); 482a18e699SShuo Chen sockets::fromHostPort(ip.c_str(), port, &addr_); 492a18e699SShuo Chen} 502a18e699SShuo Chen 51b4a5ce52SShuo Chenstd::string InetAddress::toHostPort() const 522a18e699SShuo Chen{ 532a18e699SShuo Chen char buf[32]; 542a18e699SShuo Chen sockets::toHostPort(buf, sizeof buf, addr_); 552a18e699SShuo Chen return buf; 562a18e699SShuo Chen} 572a18e699SShuo Chen 58