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