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 printf(
"Usage: %s iface destination cidr [gateway]\n", argv[0]);
19 printf(
"Example: %s eth0 10.0.1.12 32 10.0.1.11\n", argv[0]);
24 iface = if_nametoindex(argv[1]);
26 printf(
"Bad interface name\n");
31 if (!inet_pton(AF_INET, argv[2], &dst)) {
32 printf(
"Bad destination\n");
37 if (sscanf(argv[3],
"%u", &mask) == 0) {
43 if (argc >= 5 && !inet_pton(AF_INET, argv[4], &gw)) {
44 printf(
"Bad gateway\n");
49 char buf[MNL_SOCKET_BUFFER_SIZE];
54 nlh->nlmsg_type = RTM_NEWROUTE;
55 nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE;
56 nlh->nlmsg_seq = time(NULL);
59 rtm->rtm_family = AF_INET;
60 rtm->rtm_dst_len = mask;
63 rtm->rtm_protocol = RTPROT_BOOT;
64 rtm->rtm_table = RT_TABLE_MAIN;
65 rtm->rtm_type = RTN_UNICAST;
67 rtm->rtm_scope = (argc == 4) ? RT_SCOPE_LINK : RT_SCOPE_UNIVERSE;
77 perror(
"mnl_socket_open");
82 perror(
"mnl_socket_bind");
87 perror(
"mnl_socket_send");
void * mnl_nlmsg_put_extra_header(struct nlmsghdr *nlh, size_t size)
struct mnl_socket * mnl_socket_open(int type)
int mnl_socket_bind(struct mnl_socket *nl, unsigned int groups, pid_t pid)
int mnl_socket_close(struct mnl_socket *nl)
struct nlmsghdr * mnl_nlmsg_put_header(void *buf)
ssize_t mnl_socket_sendto(const struct mnl_socket *nl, const void *req, size_t siz)
void mnl_attr_put_u32(struct nlmsghdr *nlh, uint16_t type, uint32_t data)