-
-
Save woodrow/3ad5bf22c3a6c97fc2e5 to your computer and use it in GitHub Desktop.
rtnetlink_test.c
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 <stdlib.h> | |
#include <asm/types.h> | |
#include <sys/socket.h> | |
#include <linux/netlink.h> | |
#include <linux/rtnetlink.h> | |
struct sockaddr_nl sa; | |
#define handle_error(msg) \ | |
do { perror(msg); exit(EXIT_FAILURE); } while (0) | |
void read_msgs( ); | |
int fd; | |
int main (int argc, char *argv[]) | |
{ | |
int rc; | |
memset (&sa, 0, sizeof(sa)); | |
sa.nl_family = AF_NETLINK; | |
sa.nl_groups = RTMGRP_LINK; | |
fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); | |
rc = bind(fd, (struct sockaddr*)&sa, sizeof(sa)); | |
if (rc == -1) { | |
fprintf(stderr, "bind failure\n"); | |
exit(1); | |
} | |
read_msgs(); | |
return 0; | |
} | |
void read_msgs(void) | |
{ | |
int len; | |
char buf[4096]; | |
struct iovec iov = { buf, sizeof(buf) }; | |
struct msghdr nlmsg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 }; | |
struct nlmsghdr *nh; | |
struct ifinfomsg *msg; | |
struct rtattr *attr; | |
int bytes; | |
printf("enter recvmsg\n"); | |
len = recvmsg (fd, &nlmsg, 0); | |
printf("got recvmsg"); | |
for (nh = (struct nlmsghdr *) buf; NLMSG_OK (nh, len); nh = NLMSG_NEXT (nh, len)) { | |
/* The end of multipart message. */ | |
if (nh->nlmsg_type == NLMSG_DONE) | |
return; | |
if (nh->nlmsg_type == NLMSG_ERROR) { | |
printf("Error\n"); | |
/* Do some error handling. */ | |
} | |
msg = (struct ifinfomsg *) NLMSG_DATA(nh); | |
printf("link index: %d\n", msg->ifi_index); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment