SocketAddress 및 SocketAddressFactory 예제

|

SocketAddress.h

#ifndef SNOWSOCKET_SOCKETADDRESS_H
#define SNOWSOCKET_SOCKETADDRESS_H

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <memory>
#include <w32api/inaddr.h>

using namespace std;

class SocketAddress {
 public:
  SocketAddress(uint32_t address, uint16_t port) {
    getSockAddrIn()->sin_family = AF_INET;
    getSockAddrIn()->sin_addr.s_addr = htonl(address);
    getSockAddrIn()->sin_port = htons(port);
  }

  SocketAddress(string address, uint16_t port) {
    getSockAddrIn()->sin_family = AF_INET;
    getSockAddrIn()->sin_addr.s_addr = inet_addr(address.c_str());
    getSockAddrIn()->sin_port = htons(port);
  }

  SocketAddress(const sockaddr &sockAddr) {
    memcpy(&mSockAddr, &sockAddr, sizeof(sockaddr));
  }

  size_t size() const {
    return sizeof(sockaddr);
  }

 private:
  sockaddr mSockAddr;
  sockaddr_in *getSockAddrIn() {
    return reinterpret_cast<sockaddr_in *> (&mSockAddr);
  }
};

using SocketAddressPtr = shared_ptr<SocketAddress>;

#endif //SNOWSOCKET_SOCKETADDRESS_H


SocketAddressFactory.h

#ifndef SNOWSOCKET_SOCKETADDRESSFACTORY_H
#define SNOWSOCKET_SOCKETADDRESSFACTORY_H

#include <cstdio>
#include <netdb.h>
#include "SocketAddress.h"

using namespace std;

class SocketAddressFactory {
 public:
  static SocketAddressPtr createIPv4SocketAddress(const string &address) {
    string host, service;

    auto pos = address.find_last_of(':');
    if (pos != string::npos) {
      host = address.substr(0, pos);
      service = address.substr(pos + 1);
    } else {
      host = address;
      service = "0";
    }

    addrinfo hint;
    memset(&hint, 0, sizeof(hint));
    hint.ai_family = AF_INET;

    addrinfo *_result = nullptr;
    int error = getaddrinfo(host.c_str(), service.c_str(), &hint, &_result);
    addrinfo *result = _result;

    if (error != 0 && _result != nullptr) {
      freeaddrinfo(result);

      return nullptr;
    }

    while (!_result->ai_addr && _result->ai_next) {
      _result = _result->ai_next;
    }

    if (!_result->ai_addr) {
      freeaddrinfo(result);

      return nullptr;
    }

    auto toRet = make_shared<SocketAddress>(*_result->ai_addr);

    freeaddrinfo(result);

    return toRet;
  }
};

#endif //SNOWSOCKET_SOCKETADDRESSFACTORY_H