// Copyright (c) 2014, Brad Parker // This file is licensed under the BSD 2-clause license. extern "C" { #include #include #include #include #include #include } #include "utils.h" #include #include #include 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; }