Last active
November 8, 2021 12:21
-
-
Save Gottox/0fdd1fbb443dc0422464910b5313fd12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use neli::{ | |
consts::socket::NlFamily, genl::Genlmsghdr, nl::Nlmsghdr, rtnl::Ifaddrmsg, | |
socket::NlSocketHandle, | |
}; | |
fn main() -> Result<(), Box<dyn std::error::Error>> { | |
let mut s = NlSocketHandle::new(NlFamily::Route)?; | |
s.bind(None, &[0x10])?; | |
// 0x10 -> RTMGRP_IPV4_IFADDR | |
// defined in kernel header: uapi/linux/rtnetlink.h | |
for msg in s.iter(true) { | |
let header: Nlmsghdr<_, Ifaddrmsg> = msg?; | |
println!("{:#?}", header); | |
} | |
Ok(()) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <netinet/in.h> | |
#include <linux/netlink.h> | |
#include <linux/rtnetlink.h> | |
#include <net/if.h> | |
#include <arpa/inet.h> | |
int | |
main() | |
{ | |
struct sockaddr_nl addr; | |
int sock, len; | |
char buffer[4096]; | |
struct nlmsghdr *nlh; | |
if ((sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) == -1) { | |
perror("couldn't open NETLINK_ROUTE socket"); | |
return 1; | |
} | |
memset(&addr, 0, sizeof(addr)); | |
addr.nl_family = AF_NETLINK; | |
addr.nl_groups = RTMGRP_IPV4_IFADDR; | |
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) { | |
perror("couldn't bind"); | |
return 1; | |
} | |
nlh = (struct nlmsghdr *)buffer; | |
while ((len = recv(sock, nlh, 4096, 0)) > 0) { | |
while ((NLMSG_OK(nlh, len)) && (nlh->nlmsg_type != NLMSG_DONE)) { | |
if (nlh->nlmsg_type == RTM_NEWADDR) { | |
struct ifaddrmsg *ifa = (struct ifaddrmsg *) NLMSG_DATA(nlh); | |
struct rtattr *rth = IFA_RTA(ifa); | |
int rtl = IFA_PAYLOAD(nlh); | |
while (rtl && RTA_OK(rth, rtl)) { | |
if (rth->rta_type == IFA_LOCAL) { | |
char name[IFNAMSIZ]; | |
if_indextoname(ifa->ifa_index, name); | |
char ip[INET_ADDRSTRLEN]; | |
inet_ntop(AF_INET, RTA_DATA(rth), ip, sizeof(ip)); | |
printf("interface %s ip: %s\n", name, ip); | |
} | |
rth = RTA_NEXT(rth, rtl); | |
} | |
} | |
nlh = NLMSG_NEXT(nlh, len); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment