19a1e991dSShuo Chen// Copyright 2010, Shuo Chen. All rights reserved. 29a1e991dSShuo Chen// http://code.google.com/p/muduo/ 39a1e991dSShuo Chen// 49a1e991dSShuo Chen// Use of this source code is governed by a BSD-style license 59a1e991dSShuo Chen// that can be found in the License file. 69a1e991dSShuo Chen 79a1e991dSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 89a1e991dSShuo Chen 99a1e991dSShuo Chen#include "InetAddress.h" 109a1e991dSShuo Chen 119a1e991dSShuo Chen#include "SocketsOps.h" 129a1e991dSShuo Chen 139a1e991dSShuo Chen#include <strings.h> // bzero 149a1e991dSShuo Chen#include <netinet/in.h> 159a1e991dSShuo Chen 169a1e991dSShuo Chen#include <boost/static_assert.hpp> 179a1e991dSShuo Chen 189a1e991dSShuo Chen// /* Structure describing an Internet socket address. */ 199a1e991dSShuo Chen// struct sockaddr_in { 209a1e991dSShuo Chen// sa_family_t sin_family; /* address family: AF_INET */ 219a1e991dSShuo Chen// uint16_t sin_port; /* port in network byte order */ 229a1e991dSShuo Chen// struct in_addr sin_addr; /* internet address */ 239a1e991dSShuo Chen// }; 249a1e991dSShuo Chen 259a1e991dSShuo Chen// /* Internet address. */ 269a1e991dSShuo Chen// typedef uint32_t in_addr_t; 279a1e991dSShuo Chen// struct in_addr { 289a1e991dSShuo Chen// in_addr_t s_addr; /* address in network byte order */ 299a1e991dSShuo Chen// }; 309a1e991dSShuo Chen 319a1e991dSShuo Chenusing namespace muduo; 329a1e991dSShuo Chen 339a1e991dSShuo Chenstatic const in_addr_t kInaddrAny = INADDR_ANY; 349a1e991dSShuo Chen 359a1e991dSShuo ChenBOOST_STATIC_ASSERT(sizeof(InetAddress) == sizeof(struct sockaddr_in)); 369a1e991dSShuo Chen 379a1e991dSShuo ChenInetAddress::InetAddress(uint16_t port) 389a1e991dSShuo Chen{ 399a1e991dSShuo Chen bzero(&addr_, sizeof addr_); 409a1e991dSShuo Chen addr_.sin_family = AF_INET; 419a1e991dSShuo Chen addr_.sin_addr.s_addr = sockets::hostToNetwork32(kInaddrAny); 429a1e991dSShuo Chen addr_.sin_port = sockets::hostToNetwork16(port); 439a1e991dSShuo Chen} 449a1e991dSShuo Chen 45b4a5ce52SShuo ChenInetAddress::InetAddress(const std::string& ip, uint16_t port) 469a1e991dSShuo Chen{ 479a1e991dSShuo Chen bzero(&addr_, sizeof addr_); 489a1e991dSShuo Chen sockets::fromHostPort(ip.c_str(), port, &addr_); 499a1e991dSShuo Chen} 509a1e991dSShuo Chen 51b4a5ce52SShuo Chenstd::string InetAddress::toHostPort() const 529a1e991dSShuo Chen{ 539a1e991dSShuo Chen char buf[32]; 549a1e991dSShuo Chen sockets::toHostPort(buf, sizeof buf, addr_); 559a1e991dSShuo Chen return buf; 569a1e991dSShuo Chen} 579a1e991dSShuo Chen 58