#define NETWORK_INTERFACE_HPP
#include <errno.h>
-#include <net/if.h>
#include <string.h>
-#include <sys/ioctl.h>
+
+#include <arpa/inet.h>
+#include <ifaddrs.h>
+#include <netinet/in.h>
+#include <net/if.h>
#include <sys/socket.h>
#include <string>
#include <boost/assert.hpp>
#include <boost/asio/basic_socket.hpp>
#include <boost/asio/basic_raw_socket.hpp>
+#include <boost/asio/ip/address.hpp>
+#include <boost/asio/ip/address_v4.hpp>
+#include <boost/asio/ip/address_v6.hpp>
#include <logfunc.hpp>
std::string get_name() const;
- uint32_t get_address();
+ boost::asio::ip::address get_address(bool is_ip4) const;
private:
/// The network interface name which the socket is attached
return Name;
}
+#include <iostream>
+
/**
* @brief This method gets the local address of network interface.
*
- * @return The integer IP representing the local address of the network
+ * @return The integer IPv4 representing the local address of the network
* interface.
*/
template<typename SocketType>
-uint32_t NetworkInterface<SocketType>::get_address()
+boost::asio::ip::address NetworkInterface<SocketType>::get_address(bool is_ip4) const
{
+#if 0
struct ifreq ifr;
memset( &ifr, 0, sizeof(ifr) );
}
strncpy( ifr.ifr_name, Name.c_str(), network_interface_name_limit );
- ifr.ifr_addr.sa_family = AF_INET; // TODO change to AF_INET6 when IPv6
+ ifr.ifr_addr.sa_family = AF_INET6; // TODO change to AF_INET6 when IPv6 -> NAO FUNCIONOU, USAR O addr6.cpp
int ioctl_resp = ioctl( Socket.native(), SIOCGIFADDR, &ifr );
if ( ioctl_resp != 0)
const sockaddr_in *source_sockaddr = reinterpret_cast<const sockaddr_in *>( &ifr.ifr_addr );
uint32_t source_ipv4_address = htonl( source_sockaddr->sin_addr.s_addr );
+ std::cout << source_ipv4_address << std::endl;
+
return source_ipv4_address;
+#endif
+
+ struct ifaddrs *ifa_first = NULL;
+ struct ifaddrs *ifa_current = NULL;
+ int rc = 0;
+ char addr_string[ INET6_ADDRSTRLEN ];
+
+ rc = getifaddrs( &ifa_first );
+ if ( rc == 0 )
+ {
+ for ( ifa_current = ifa_first; ifa_current != NULL; ifa_current = ifa_current->ifa_next )
+ {
+ if ( ifa_current->ifa_addr->sa_data == NULL)
+ {
+ continue;
+ }
+
+ char *interface_name = ifa_current->ifa_name;
+ if ( Name == interface_name )
+ {
+ sa_family_t addr_type = ifa_current->ifa_addr->sa_family;
+ void *addr_bytes = NULL;
+
+ if ( AF_INET == addr_type )
+ {
+ addr_bytes = &((struct sockaddr_in *) ifa_current->ifa_addr)->sin_addr;
+ }
+ else if ( AF_INET6 == addr_type )
+ {
+ addr_bytes = &((struct sockaddr_in6 *) ifa_current->ifa_addr)->sin6_addr;
+ }
+
+ if ( addr_bytes != NULL )
+ {
+ const char *a = inet_ntop( addr_type, addr_bytes, addr_string, sizeof(addr_string) );
+ if ( a != NULL )
+ {
+ if ( AF_INET == addr_type )
+ {
+ return boost::asio::ip::address_v4::from_string( std::string( a ) );
+ }
+ else if ( AF_INET6 == addr_type )
+ {
+ return boost::asio::ip::address_v6::from_string( std::string( a ) );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ freeifaddrs( ifa_first );
}
#endif // NETWORK_INTERFACE_HPP