InetAddress.cc revision 40161064
140161064SShuo Chen// Copyright 2010, Shuo Chen. All rights reserved. 240161064SShuo Chen// http://code.google.com/p/muduo/ 340161064SShuo Chen// 440161064SShuo Chen// Use of this source code is governed by a BSD-style license 540161064SShuo Chen// that can be found in the License file. 640161064SShuo Chen 740161064SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 840161064SShuo Chen 940161064SShuo Chen#include "InetAddress.h" 1040161064SShuo Chen 1140161064SShuo Chen#include "SocketsOps.h" 1240161064SShuo Chen 1340161064SShuo Chen#include <strings.h> // bzero 1440161064SShuo Chen#include <netinet/in.h> 1540161064SShuo Chen 1640161064SShuo Chen#include <boost/static_assert.hpp> 1740161064SShuo Chen 1840161064SShuo Chen// /* Structure describing an Internet socket address. */ 1940161064SShuo Chen// struct sockaddr_in { 2040161064SShuo Chen// sa_family_t sin_family; /* address family: AF_INET */ 2140161064SShuo Chen// uint16_t sin_port; /* port in network byte order */ 2240161064SShuo Chen// struct in_addr sin_addr; /* internet address */ 2340161064SShuo Chen// }; 2440161064SShuo Chen 2540161064SShuo Chen// /* Internet address. */ 2640161064SShuo Chen// typedef uint32_t in_addr_t; 2740161064SShuo Chen// struct in_addr { 2840161064SShuo Chen// in_addr_t s_addr; /* address in network byte order */ 2940161064SShuo Chen// }; 3040161064SShuo Chen 3140161064SShuo Chenusing namespace muduo; 3240161064SShuo Chen 3340161064SShuo Chenstatic const in_addr_t kInaddrAny = INADDR_ANY; 3440161064SShuo Chen 3540161064SShuo ChenBOOST_STATIC_ASSERT(sizeof(InetAddress) == sizeof(struct sockaddr_in)); 3640161064SShuo Chen 3740161064SShuo ChenInetAddress::InetAddress(uint16_t port) 3840161064SShuo Chen{ 3940161064SShuo Chen bzero(&addr_, sizeof addr_); 4040161064SShuo Chen addr_.sin_family = AF_INET; 4140161064SShuo Chen addr_.sin_addr.s_addr = sockets::hostToNetwork32(kInaddrAny); 4240161064SShuo Chen addr_.sin_port = sockets::hostToNetwork16(port); 4340161064SShuo Chen} 4440161064SShuo Chen 4540161064SShuo ChenInetAddress::InetAddress(const std::string& ip, uint16_t port) 4640161064SShuo Chen{ 4740161064SShuo Chen bzero(&addr_, sizeof addr_); 4840161064SShuo Chen sockets::fromHostPort(ip.c_str(), port, &addr_); 4940161064SShuo Chen} 5040161064SShuo Chen 5140161064SShuo Chenstd::string InetAddress::toHostPort() const 5240161064SShuo Chen{ 5340161064SShuo Chen char buf[32]; 5440161064SShuo Chen sockets::toHostPort(buf, sizeof buf, addr_); 5540161064SShuo Chen return buf; 5640161064SShuo Chen} 5740161064SShuo Chen 58