165c497a3SShuo Chen// Copyright 2010, Shuo Chen. All rights reserved. 265c497a3SShuo Chen// http://code.google.com/p/muduo/ 365c497a3SShuo Chen// 465c497a3SShuo Chen// Use of this source code is governed by a BSD-style license 565c497a3SShuo Chen// that can be found in the License file. 665c497a3SShuo Chen 765c497a3SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 865c497a3SShuo Chen 965c497a3SShuo Chen#include "InetAddress.h" 1065c497a3SShuo Chen 1165c497a3SShuo Chen#include "SocketsOps.h" 1265c497a3SShuo Chen 1365c497a3SShuo Chen#include <strings.h> // bzero 1465c497a3SShuo Chen#include <netinet/in.h> 1565c497a3SShuo Chen 1665c497a3SShuo Chen#include <boost/static_assert.hpp> 1765c497a3SShuo Chen 1865c497a3SShuo Chen// /* Structure describing an Internet socket address. */ 1965c497a3SShuo Chen// struct sockaddr_in { 2065c497a3SShuo Chen// sa_family_t sin_family; /* address family: AF_INET */ 2165c497a3SShuo Chen// uint16_t sin_port; /* port in network byte order */ 2265c497a3SShuo Chen// struct in_addr sin_addr; /* internet address */ 2365c497a3SShuo Chen// }; 2465c497a3SShuo Chen 2565c497a3SShuo Chen// /* Internet address. */ 2665c497a3SShuo Chen// typedef uint32_t in_addr_t; 2765c497a3SShuo Chen// struct in_addr { 2865c497a3SShuo Chen// in_addr_t s_addr; /* address in network byte order */ 2965c497a3SShuo Chen// }; 3065c497a3SShuo Chen 3165c497a3SShuo Chenusing namespace muduo; 3265c497a3SShuo Chen 3365c497a3SShuo Chenstatic const in_addr_t kInaddrAny = INADDR_ANY; 3465c497a3SShuo Chen 3565c497a3SShuo ChenBOOST_STATIC_ASSERT(sizeof(InetAddress) == sizeof(struct sockaddr_in)); 3665c497a3SShuo Chen 3765c497a3SShuo ChenInetAddress::InetAddress(uint16_t port) 3865c497a3SShuo Chen{ 3965c497a3SShuo Chen bzero(&addr_, sizeof addr_); 4065c497a3SShuo Chen addr_.sin_family = AF_INET; 4165c497a3SShuo Chen addr_.sin_addr.s_addr = sockets::hostToNetwork32(kInaddrAny); 4265c497a3SShuo Chen addr_.sin_port = sockets::hostToNetwork16(port); 4365c497a3SShuo Chen} 4465c497a3SShuo Chen 45b4a5ce52SShuo ChenInetAddress::InetAddress(const std::string& ip, uint16_t port) 4665c497a3SShuo Chen{ 4765c497a3SShuo Chen bzero(&addr_, sizeof addr_); 4865c497a3SShuo Chen sockets::fromHostPort(ip.c_str(), port, &addr_); 4965c497a3SShuo Chen} 5065c497a3SShuo Chen 51b4a5ce52SShuo Chenstd::string InetAddress::toHostPort() const 5265c497a3SShuo Chen{ 5365c497a3SShuo Chen char buf[32]; 5465c497a3SShuo Chen sockets::toHostPort(buf, sizeof buf, addr_); 5565c497a3SShuo Chen return buf; 5665c497a3SShuo Chen} 5765c497a3SShuo Chen 58