aboutsummaryrefslogtreecommitdiff
path: root/src/IpAddress.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/IpAddress.cpp')
-rw-r--r--src/IpAddress.cpp40
1 files changed, 40 insertions, 0 deletions
diff --git a/src/IpAddress.cpp b/src/IpAddress.cpp
new file mode 100644
index 0000000..22e81e5
--- /dev/null
+++ b/src/IpAddress.cpp
@@ -0,0 +1,40 @@
+#include "../include/sibs/IpAddress.hpp"
+#include <cstring>
+
+namespace sibs
+{
+ Ipv4::Ipv4(const char *ip, unsigned short port)
+ {
+ address.sin_family = AF_INET;
+ address.sin_port = htons(port);
+ if(ip)
+ {
+ if(strlen(ip) > 15)
+ throw InvalidAddressException("Ip address is too long");
+
+ if(inet_pton(AF_INET, ip, &address.sin_addr.s_addr) != 1)
+ {
+ std::string errMsg = "Ip ";
+ errMsg += ip;
+ errMsg += " is not a valid ip";
+ throw InvalidAddressException(errMsg);
+ }
+ }
+ else
+ address.sin_addr.s_addr = INADDR_ANY;
+ memset(address.sin_zero, 0, sizeof(address.sin_zero));
+ }
+
+ std::string Ipv4::getAddress() const
+ {
+ std::string result;
+ result.resize(INET_ADDRSTRLEN);
+ inet_ntop(AF_INET, &address.sin_addr, &result[0], INET_ADDRSTRLEN);
+ return result;
+ }
+
+ unsigned short Ipv4::getPort() const
+ {
+ return ntohs(address.sin_port);
+ }
+}