5 #include <netlink/netlink.h>
6 #include <netlink/genl/genl.h>
7 #include <netlink/genl/ctrl.h>
9 #include "nbd-netlink.h"
11 static struct nla_policy nbd_device_policy
[NBD_DEVICE_ATTR_MAX
+ 1] = {
12 [NBD_DEVICE_INDEX
] = { .type
= NLA_U32
},
13 [NBD_DEVICE_CONNECTED
] = { .type
= NLA_U8
},
16 static struct nl_sock
*get_nbd_socket(int *driver_id
)
18 struct nl_sock
*socket
;
21 socket
= nl_socket_alloc();
23 err("Couldn't allocate netlink socket\n");
25 if (genl_connect(socket
))
26 err("Couldn't connect to the generic netlink socket\n");
27 id
= genl_ctrl_resolve(socket
, "nbd");
29 err("Couldn't resolve the nbd netlink family, make sure the nbd module is loaded and your nbd driver supports the netlink interface.\n");
35 static int callback(struct nl_msg
*msg
, void *arg
)
37 struct genlmsghdr
*gnlh
= nlmsg_data(nlmsg_hdr(msg
));
38 struct nlattr
*msg_attr
[NBD_ATTR_MAX
+ 1];
42 ret
= nla_parse(msg_attr
, NBD_ATTR_MAX
, genlmsg_attrdata(gnlh
, 0),
43 genlmsg_attrlen(gnlh
, 0), NULL
);
45 err("Invalid response from get status?\n");
47 nla_for_each_nested(attr
, msg_attr
[NBD_ATTR_DEVICE_LIST
], rem
) {
48 struct nlattr
*device
[NBD_DEVICE_ATTR_MAX
+ 1];
52 if (nla_type(attr
) != NBD_DEVICE_ITEM
)
53 err("Invalid attr type in the device list\n");
54 ret
= nla_parse_nested(device
, NBD_DEVICE_ATTR_MAX
, attr
,
57 err("Invalid attr device attr\n");
58 index
= nla_get_u32(device
[NBD_DEVICE_INDEX
]);
59 connected
= nla_get_u8(device
[NBD_DEVICE_CONNECTED
]);
60 printf("/dev/nbd%d: %s\n", (int)index
,
61 connected
? "connected" : "disconnected");
66 int main(int argc
, char **argv
)
68 struct nl_sock
*socket
;
69 struct nlattr
*sock_attr
;
75 if (sscanf(argv
[1], "/dev/nbd%d", &index
) != 1)
76 err("Invalid nbd device target\n");
79 socket
= get_nbd_socket(&driver_id
);
80 nl_socket_modify_cb(socket
, NL_CB_VALID
, NL_CB_CUSTOM
, callback
, NULL
);
84 err("Couldn't allocate netlink message\n");
85 genlmsg_put(msg
, NL_AUTO_PORT
, NL_AUTO_SEQ
, driver_id
, 0, 0,
88 NLA_PUT_U32(msg
, NBD_ATTR_INDEX
, index
);
89 if (nl_send_sync(socket
, msg
) < 0)
90 err("Failed to get status\n");
93 err("Failed to create netlink message\n");