libmnl  1.0.3
rtnl-link-set.c
00001 /* This example is placed in the public domain. */
00002 #include <stdio.h>
00003 #include <stdlib.h>
00004 #include <unistd.h>
00005 #include <string.h>
00006 #include <time.h>
00007 
00008 #include <libmnl/libmnl.h>
00009 #include <linux/if.h>
00010 #include <linux/if_link.h>
00011 #include <linux/rtnetlink.h>
00012 
00013 int main(int argc, char *argv[])
00014 {
00015         struct mnl_socket *nl;
00016         char buf[MNL_SOCKET_BUFFER_SIZE];
00017         struct nlmsghdr *nlh;
00018         struct ifinfomsg *ifm;
00019         int ret;
00020         unsigned int seq, portid, change = 0, flags = 0;
00021 
00022         if (argc != 3) {
00023                 printf("Usage: %s [ifname] [up|down]\n", argv[0]);
00024                 exit(EXIT_FAILURE);
00025         }
00026 
00027         if (strncasecmp(argv[2], "up", strlen("up")) == 0) {
00028                 change |= IFF_UP;
00029                 flags |= IFF_UP;
00030         } else if (strncasecmp(argv[2], "down", strlen("down")) == 0) {
00031                 change |= IFF_UP;
00032                 flags &= ~IFF_UP;
00033         } else {
00034                 fprintf(stderr, "%s is not `up' nor `down'\n", argv[2]);
00035                 exit(EXIT_FAILURE);
00036         }
00037 
00038         nlh = mnl_nlmsg_put_header(buf);
00039         nlh->nlmsg_type = RTM_NEWLINK;
00040         nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
00041         nlh->nlmsg_seq = seq = time(NULL);
00042         ifm = mnl_nlmsg_put_extra_header(nlh, sizeof(*ifm));
00043         ifm->ifi_family = AF_UNSPEC;
00044         ifm->ifi_change = change;
00045         ifm->ifi_flags = flags;
00046 
00047         mnl_attr_put_str(nlh, IFLA_IFNAME, argv[1]);
00048 
00049         nl = mnl_socket_open(NETLINK_ROUTE);
00050         if (nl == NULL) {
00051                 perror("mnl_socket_open");
00052                 exit(EXIT_FAILURE);
00053         }
00054 
00055         if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
00056                 perror("mnl_socket_bind");
00057                 exit(EXIT_FAILURE);
00058         }
00059         portid = mnl_socket_get_portid(nl);
00060 
00061         mnl_nlmsg_fprintf(stdout, nlh, nlh->nlmsg_len,
00062                           sizeof(struct ifinfomsg));
00063 
00064         if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
00065                 perror("mnl_socket_send");
00066                 exit(EXIT_FAILURE);
00067         }
00068 
00069         ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
00070         if (ret == -1) {
00071                 perror("read");
00072                 exit(EXIT_FAILURE);
00073         }
00074 
00075         ret = mnl_cb_run(buf, ret, seq, portid, NULL, NULL);
00076         if (ret == -1){
00077                 perror("callback");
00078                 exit(EXIT_FAILURE);
00079         }
00080 
00081         mnl_socket_close(nl);
00082 
00083         return 0;
00084 }