setting multiple ip addresses for an interface

Haris Rotsos cr409 at cl.cam.ac.uk
Thu Nov 25 15:02:43 EST 2010


Hello everybody,

I am currently trying to create a program that will act similarly as
the command ip addr add XXX.XXX.XXX.XXX dev oftap3.

I have written the following code using libnl:

#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <unistd.h>
#include <fcntl.h>


//#include <netlink-local.h>

//#include <nl.h>

int
main(int argc, char **argv) {
  struct rtnl_addr *addr;
  struct nl_cache *cache;
  struct nl_sock *sk;
  struct nl_addr *local_addr;
  int ifindex;

  if(argc < 2) {
    printf("Invalid number of arguments\n Usage: ./set_ip %%ip%%\n");
    return 1;
  }
  printf("setting ip %s to oftap3....\n", argv[1]);

  // Allocate an empty address object to be filled out with the attributes
  // of the new address.
  addr = rtnl_addr_alloc();
  if(addr == NULL) {
    perror("addr alloc");
    return 1;
  }

  sk = nl_socket_alloc();
  if(sk == NULL) {
    perror("socket alloc");
    return 1;
  }
  if(nl_connect(sk, NETLINK_ROUTE) != 0) {
    perror("nl connect");
    return 1;
  }

  if(rtnl_link_alloc_cache(sk, &cache) !=0 ) {
    perror("alloc cache");
    return 1;
  }
  ifindex = rtnl_link_name2i(cache, "oftap3");
  if(ifindex == 0) {
    perror("name2i");
    return 1;
  }
  rtnl_addr_set_ifindex(addr, ifindex);

  if(nl_addr_parse (argv[1], AF_INET, &local_addr) != 0) {
    perror("addr parse");
    return 1;
  }

  char tmp[1024];
  nl_addr2str (local_addr, tmp, 1024);
  printf("setting ip %s on intf oftap3(%d)\n", tmp, ifindex);
  if(rtnl_addr_set_local(addr, local_addr) != 0) {
    perror("addr_set_local");
    return 1;
  }

 //rtnl_addr_set_label(addr, "mylabel");
 //rtnl_addr_set_peer(addr, peer_addr);
 //rtnl_addr_set_scope(addr, rtnl_str2scope("global"));
 //rtnl_addr_set_broadcast(addr, broadcast_addr);

 if(rtnl_addr_add(sk, addr, 0) != 0) {
   perror("addr_add");
   return 1;
  }
 // Free the memory
 rtnl_addr_put(addr);

 //removing state
 nl_close(sk);
 nl_socket_free (sk);
}



Can somebody help and tell if I am doing something wrong?

During execution command rtnl_addr_add returns a negative value.

-- 
Charalampos Rotsos
PhD student
The University of Cambridge
Computer Laboratory
William Gates Building
JJ Thomson Avenue
Cambridge
CB3 0FD

Phone: +44-(0) 1223 767032
Email: cr409 at cl.cam.ac.uk



More information about the libnl mailing list