HEBI C++ API  3.9.0
ip_address.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include "hebi.h"
4 
5 #include <iostream>
6 
7 #ifdef WIN32
8 
9 #define NOMINMAX
10 #include <ws2tcpip.h>
11 #include <stdlib.h>
12 #define bswap_32(x) _byteswap_ulong(x)
13 using in_addr_t = in_addr;
14 
15 #elif defined(__APPLE__)
16 
17 // Mac OS X / Darwin features
18 #include <libkern/OSByteOrder.h>
19 #define bswap_32(x) OSSwapInt32(x)
20 #include <arpa/inet.h>
21 
22 #else // Linux
23 
24 #include <arpa/inet.h>
25 #include <byteswap.h>
26 
27 #endif
28 
29 namespace hebi {
30 
34 class IpAddress final {
35 public:
39  IpAddress() = default;
40 
41  // Create IP Address from network order uint32_t
42  IpAddress(uint32_t address_raw) : address_network_order_(address_raw) {}
43 
47  static IpAddress fromBytes(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
48  // TODO: depends on byte order:
49  uint32_t tmp = (a << 24) | (b << 16) | (c << 8) | (d);
50  return IpAddress(tmp);
51  }
52 
56  static IpAddress fromLittleEndian(uint32_t raw) {
57  return IpAddress(bswap_32(raw));
58  }
59 
69  bool setToString(const std::string& ip_str) {
70  in_addr_t addr;
71  if (inet_pton(AF_INET, ip_str.c_str(), &addr) != 1)
72  return false;
73  #ifdef WIN32
74  address_network_order_ = addr.S_un.S_addr;
75  #else
76  address_network_order_ = addr;
77  #endif
78  return true;
79  }
80 
84  std::string toString() const {
85  std::string res;
86  res.resize(INET_ADDRSTRLEN);
87  inet_ntop(AF_INET, &address_network_order_, &res[0], INET_ADDRSTRLEN);
88  return res;
89  }
90 
94  uint32_t getLittleEndian() const {
95  return bswap_32(address_network_order_);
96  }
97 
101  uint32_t getBigEndian() const {
102  return address_network_order_;
103  }
104 
105 private:
106  uint32_t address_network_order_{};
107 };
108 
109 } // namespace hebi
uint32_t getBigEndian() const
Returns the IP Address as a big endian (network order) uint32_t.
Definition: ip_address.hpp:101
static IpAddress fromLittleEndian(uint32_t raw)
Creates an IpAddress from a little endian uint32_t.
Definition: ip_address.hpp:56
Definition: arm.cpp:8
bool setToString(const std::string &ip_str)
Sets the value of the current IpAddress to the value given in 'ip_str'.
Definition: ip_address.hpp:69
IpAddress(uint32_t address_raw)
Definition: ip_address.hpp:42
std::string toString() const
Returns a string representation of the IP address.
Definition: ip_address.hpp:84
static IpAddress fromBytes(uint8_t a, uint8_t b, uint8_t c, uint8_t d)
Creates an IpAddress from individual bytes.
Definition: ip_address.hpp:47
uint32_t getLittleEndian() const
Returns the IP Address as a little endian uint32_t.
Definition: ip_address.hpp:94
A simple wrapper class for IpAddress objects.
Definition: ip_address.hpp:34
IpAddress()=default
Creates IPv4 address 0.0.0.0.