1 #ifndef POSIXX_SOCKET_INET_HPP_
2 #define POSIXX_SOCKET_INET_HPP_
4 #include "../basic_socket.hpp" // posixx::socket
6 #include <netinet/in.h> // sockaddr_in, htonl, htons, {PF,AF}_INET, INADDR_ANY
7 #include <arpa/inet.h> // inet_addr
8 #include <cstring> // memset
9 #include <string> // std::string
13 namespace posixx { namespace socket {
15 /// Internet Protocol sockets
19 struct sockaddr: sockaddr_in
23 * Create an IP socket address.
25 sockaddr(u_int16_t port = 0, const std::string& ip = "0.0.0.0")
28 /// Length of this IP socket address
29 socklen_t length() const throw ();
31 /// Compare two IP socket addresses
32 bool operator == (const sockaddr& other) const throw ();
34 /// Get the port number
35 uint16_t port() const throw ();
37 /// Get the IP address
38 std::string addr() const throw ();
45 /// Socket address type.
46 typedef inet::sockaddr sockaddr;
48 enum { PF = PF_INET };
52 typedef posixx::socket::basic_socket< traits > socket;
54 } } } // namespace posixx::socket::inet
60 posixx::socket::inet::sockaddr::sockaddr(u_int16_t port, const std::string& ip)
63 memset(this, 0, sizeof(struct sockaddr_in));
65 if (ip == "0.0.0.0") {
66 sin_addr.s_addr = htonl(INADDR_ANY);
69 sin_addr.s_addr = inet_addr(ip.c_str());
71 sin_port = htons(port);
75 socklen_t posixx::socket::inet::sockaddr::length() const throw ()
77 return sizeof(sockaddr_in);
81 bool posixx::socket::inet::sockaddr::operator == (const sockaddr& other) const
84 return !memcmp(this, &other, sizeof(*this));
88 uint16_t posixx::socket::inet::sockaddr::port() const throw ()
90 return ntohs(sin_port);
94 std::string posixx::socket::inet::sockaddr::addr() const throw ()
96 return inet_ntoa(sin_addr);
99 #endif // POSIXX_SOCKET_INET_HPP_