You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

95 lines
2.1 KiB

extern "C" {
#include <pthread.h>
#include <netlink/socket.h>
#include <linux/netlink.h>
#include <netlink/netlink.h>
#include <netlink/route/addr.h>
#include <netlink/route/neighbour.h>
}
#include "utils.h"
#include <iostream>
#include <QTimer>
#include <QtCore/QCoreApplication>
struct nl_sock* Utils::connect() {
struct nl_sock *sock = nl_socket_alloc();
int err = 0;
if(sock == NULL) {
std::cerr << "could not allocate netlink socket" << std::endl;
return NULL;
}
if((err = nl_connect(sock, NETLINK_ROUTE)) < 0) {
std::cerr << "could not connect to netlink socket: " << nl_geterror(err) << std::endl;
nl_socket_free(sock);
return NULL;
}
return sock;
}
int Utils::alloc_addr_cache(struct nl_sock *sock, struct nl_cache **cache) {
int err = 0;
if((err = rtnl_addr_alloc_cache(sock, cache)) < 0) {
std::cerr << "could not allocate address cache: " << nl_geterror(err) << std::endl;
return 1;
}
nl_cache_mngt_provide(*cache);
return 0;
}
int Utils::alloc_link_cache(struct nl_sock *sock, struct nl_cache **cache) {
int err = rtnl_link_alloc_cache(sock, AF_UNSPEC, cache);
if(err != 0) {
std::cerr << "could not allocate link cache: " << nl_geterror(err) << std::endl;
return 1;
}
nl_cache_mngt_provide(*cache);
return 0;
}
int Utils::alloc_neigh_cache(struct nl_sock *sock, struct nl_cache **cache) {
int err = 0;
if((err = rtnl_neigh_alloc_cache(sock, cache)) < 0) {
std::cerr << "could not allocate neighbor cache: " << nl_geterror(err) << std::endl;
return 1;
}
nl_cache_mngt_provide(*cache);
return 0;
}
int Utils::interfaceIndex(QString interface) {
QByteArray array = interface.toLatin1();
struct nl_sock *sock = Utils::connect();
if(!sock) {
std::cerr << "could not allocate socket" << std::endl;
return 0;
}
const char *interfaceData = array.constData();
struct nl_cache *link_cache = NULL;
if(Utils::alloc_link_cache(sock, &link_cache)) {
nl_socket_free(sock);
return 0;
}
int index = rtnl_link_name2i(link_cache, interfaceData);
nl_cache_free(link_cache);
nl_socket_free(sock);
return index;
}