11#include <libmnl/libmnl.h>
12#include <linux/if_link.h>
13#include <linux/rtnetlink.h>
15int main(
int argc,
char *argv[])
17 struct mnl_socket *nl;
18 char buf[MNL_SOCKET_BUFFER_SIZE];
21 uint32_t prefix, seq, portid;
30 int iface, ret, family = AF_INET;
33 printf(
"Usage: %s iface destination cidr [gateway]\n", argv[0]);
34 printf(
"Example: %s eth0 10.0.1.12 32 10.0.1.11\n", argv[0]);
35 printf(
" %s eth0 ffff::10.0.1.12 128 fdff::1\n", argv[0]);
39 iface = if_nametoindex(argv[1]);
41 perror(
"if_nametoindex");
45 if (!inet_pton(AF_INET, argv[2], &dst)) {
46 if (!inet_pton(AF_INET6, argv[2], &dst)) {
53 if (sscanf(argv[3],
"%u", &prefix) == 0) {
58 if (argc == 5 && !inet_pton(family, argv[4], &gw)) {
64 nlh->nlmsg_type = RTM_NEWROUTE;
65 nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK;
66 nlh->nlmsg_seq = seq = time(NULL);
69 rtm->rtm_family = family;
70 rtm->rtm_dst_len = prefix;
73 rtm->rtm_protocol = RTPROT_STATIC;
74 rtm->rtm_table = RT_TABLE_MAIN;
75 rtm->rtm_type = RTN_UNICAST;
77 rtm->rtm_scope = (argc == 4) ? RT_SCOPE_LINK : RT_SCOPE_UNIVERSE;
80 if (family == AF_INET)
83 mnl_attr_put(nlh, RTA_DST,
sizeof(
struct in6_addr), &dst);
87 if (family == AF_INET)
97 perror(
"mnl_socket_open");
102 perror(
"mnl_socket_bind");
108 perror(
"mnl_socket_sendto");
114 perror(
"mnl_socket_recvfrom");
118 ret =
mnl_cb_run(buf, ret, seq, portid, NULL, NULL);
120 perror(
"mnl_cb_run");
void mnl_attr_put_u32(struct nlmsghdr *nlh, uint16_t type, uint32_t data)
void mnl_attr_put(struct nlmsghdr *nlh, uint16_t type, size_t len, const void *data)
int mnl_cb_run(const void *buf, size_t numbytes, unsigned int seq, unsigned int portid, mnl_cb_t cb_data, void *data)
struct nlmsghdr * mnl_nlmsg_put_header(void *buf)
void * mnl_nlmsg_put_extra_header(struct nlmsghdr *nlh, size_t size)
int mnl_socket_close(struct mnl_socket *nl)
unsigned int mnl_socket_get_portid(const struct mnl_socket *nl)
struct mnl_socket * mnl_socket_open(int bus)
ssize_t mnl_socket_recvfrom(const struct mnl_socket *nl, void *buf, size_t bufsiz)
int mnl_socket_bind(struct mnl_socket *nl, unsigned int groups, pid_t pid)
ssize_t mnl_socket_sendto(const struct mnl_socket *nl, const void *buf, size_t len)