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