libmnl  1.0.4
rtnl-link-set.c
1 /* This example is placed in the public domain. */
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <time.h>
7 
8 #include <libmnl/libmnl.h>
9 #include <linux/if.h>
10 #include <linux/if_link.h>
11 #include <linux/rtnetlink.h>
12 
13 int main(int argc, char *argv[])
14 {
15  struct mnl_socket *nl;
16  char buf[MNL_SOCKET_BUFFER_SIZE];
17  struct nlmsghdr *nlh;
18  struct ifinfomsg *ifm;
19  int ret;
20  unsigned int seq, portid, change = 0, flags = 0;
21 
22  if (argc != 3) {
23  printf("Usage: %s [ifname] [up|down]\n", argv[0]);
24  exit(EXIT_FAILURE);
25  }
26 
27  if (strncasecmp(argv[2], "up", strlen("up")) == 0) {
28  change |= IFF_UP;
29  flags |= IFF_UP;
30  } else if (strncasecmp(argv[2], "down", strlen("down")) == 0) {
31  change |= IFF_UP;
32  flags &= ~IFF_UP;
33  } else {
34  fprintf(stderr, "%s is not `up' nor `down'\n", argv[2]);
35  exit(EXIT_FAILURE);
36  }
37 
38  nlh = mnl_nlmsg_put_header(buf);
39  nlh->nlmsg_type = RTM_NEWLINK;
40  nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
41  nlh->nlmsg_seq = seq = time(NULL);
42  ifm = mnl_nlmsg_put_extra_header(nlh, sizeof(*ifm));
43  ifm->ifi_family = AF_UNSPEC;
44  ifm->ifi_change = change;
45  ifm->ifi_flags = flags;
46 
47  mnl_attr_put_str(nlh, IFLA_IFNAME, argv[1]);
48 
49  nl = mnl_socket_open(NETLINK_ROUTE);
50  if (nl == NULL) {
51  perror("mnl_socket_open");
52  exit(EXIT_FAILURE);
53  }
54 
55  if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
56  perror("mnl_socket_bind");
57  exit(EXIT_FAILURE);
58  }
59  portid = mnl_socket_get_portid(nl);
60 
61  mnl_nlmsg_fprintf(stdout, nlh, nlh->nlmsg_len,
62  sizeof(struct ifinfomsg));
63 
64  if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
65  perror("mnl_socket_sendto");
66  exit(EXIT_FAILURE);
67  }
68 
69  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
70  if (ret == -1) {
71  perror("mnl_socket_recvfrom");
72  exit(EXIT_FAILURE);
73  }
74 
75  ret = mnl_cb_run(buf, ret, seq, portid, NULL, NULL);
76  if (ret == -1){
77  perror("mnl_cb_run");
78  exit(EXIT_FAILURE);
79  }
80 
81  mnl_socket_close(nl);
82 
83  return 0;
84 }