2 #include <netinet/in.h>
11 #include <libmnl/libmnl.h>
12 #include <linux/if_link.h>
13 #include <linux/rtnetlink.h>
15 int main(
int argc,
char *argv[])
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)) {
63 nlh = mnl_nlmsg_put_header(buf);
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);
68 rtm = mnl_nlmsg_put_extra_header(nlh,
sizeof(
struct rtmsg));
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)
81 mnl_attr_put_u32(nlh, RTA_DST, dst.ip);
83 mnl_attr_put(nlh, RTA_DST,
sizeof(
struct in6_addr), &dst);
85 mnl_attr_put_u32(nlh, RTA_OIF, iface);
87 if (family == AF_INET)
88 mnl_attr_put_u32(nlh, RTA_GATEWAY, gw.ip);
90 mnl_attr_put(nlh, RTA_GATEWAY,
sizeof(
struct in6_addr),
95 nl = mnl_socket_open(NETLINK_ROUTE);
97 perror(
"mnl_socket_open");
101 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
102 perror(
"mnl_socket_bind");
105 portid = mnl_socket_get_portid(nl);
107 if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
108 perror(
"mnl_socket_sendto");
112 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
114 perror(
"mnl_socket_recvfrom");
118 ret = mnl_cb_run(buf, ret, seq, portid, NULL, NULL);
120 perror(
"mnl_cb_run");
124 mnl_socket_close(nl);