Sleds/gluster_status/Network.h

64 lines
2.6 KiB
C++

/*
Copyright (c) 2014 IOnU Security Inc. All rights reserved
Created February 2014 by Kendrick Webster
Network.h - header for network utilities
*/
#pragma once
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <list>
#include "Types.h"
#include "LogTrace.h"
namespace ionu { namespace network {
constexpr uint32_t LOOPBACK_ADDRESS = 0x7F000001; // in host byte order, 127.0.0.1
constexpr unsigned int ADDRESS_STRING_LENGTH = (INET6_ADDRSTRLEN > INET_ADDRSTRLEN) ? INET6_ADDRSTRLEN : INET_ADDRSTRLEN;
struct CHost
{
std::string host;
uint16_t port; // in host byte order
CHost(std::string h, uint16_t p = 0) : host(h), port(p) {}
};
typedef std::list<CHost> host_list_t;
struct CAddress
{
uint32_t addr; // in network byte order
uint16_t port; // ditto
CAddress(uint32_t a, uint16_t p) : addr(a), port(p) {}
CAddress() : addr(htonl(LOOPBACK_ADDRESS)), port(0) {}
bool operator== (const CAddress& x) const {return (addr == x.addr) && (port == x.port);}
bool operator!= (const CAddress& x) const {return !(*this == x);}
uint64_t AsUint64(void) const {return (static_cast<uint64_t>(ntohl(addr)) << 16 | ntohs(port));}
bool operator< (const CAddress& x) const {return AsUint64() < x.AsUint64();}
bool operator> (const CAddress& x) const {return AsUint64() > x.AsUint64();}
};
typedef std::list<CAddress> address_list_t;
// converts <a> to dotted-decimal string
std::string IP4AddressString(struct in_addr a);
std::string IP4AddressString(uint32_t a); // network byte order
std::string IP4AddressString(CAddress a); // ignores <a.port>
std::string IP4AddressString(const struct sockaddr_in& a); // uses <a.sin_addr.s_addr>, ignores the rest
// host name lookup
success_t HostToAddress(const CHost& h, CAddress& a,
int socktype = SOCK_DGRAM, // hint for getaddrinfo(), only results matching this type are used
Log::severity_t trace_loglevel = Log::debug, // severity for logging resolved addresses
Log::severity_t error_loglevel = Log::error); // severity for logging errors (i.e. lookup failed)
// host name lookup for lists,
// returns FAILURE if one or more lookups fails (then <al> contains partial results)
success_t HostListToAddressList(const host_list_t& hl, address_list_t& al,
int socktype = SOCK_DGRAM, // hint for getaddrinfo(), only results matching this type are used
Log::severity_t trace_loglevel = Log::debug, // severity for logging resolved addresses
Log::severity_t error_loglevel = Log::error); // severity for logging errors (i.e. lookup failed)
}}