+
+ // Prepare socket for link events
+ if ((nl_cb_rtnl_event = nl_cb_alloc(NL_CB_DEFAULT)))
+ nl_cb_set(nl_cb_rtnl_event, NL_CB_VALID, NL_CB_CUSTOM,
+ cb_rtnl_event, NULL);
+
+ if (nl_cb_rtnl_event && (sock_rtnl_event = nl_socket_alloc())) {
+ if (nl_connect(sock_rtnl_event, NETLINK_ROUTE)) {
+ nl_socket_free(sock_rtnl_event);
+ sock_rtnl_event = NULL;
+ }
+ // Receive network link events form kernel
+ nl_socket_add_membership(sock_rtnl_event, RTNLGRP_LINK);
+
+ // Synthesize initial link messages
+ struct nl_msg *m = nlmsg_alloc_simple(RTM_GETLINK, NLM_F_DUMP);
+ if (m && nlmsg_reserve(m, sizeof(struct ifinfomsg), 0)) {
+ nl_send_auto_complete(sock_rtnl_event, m);
+ nlmsg_free(m);
+ }
+
+ rtnl_event.fd = nl_socket_get_fd(sock_rtnl_event);
+ uloop_fd_add(&rtnl_event, ULOOP_READ | ULOOP_EDGE_TRIGGER);
+ }
+
+ return -(sock_ioctl < 0 || !sock_rtnl);
+}
+
+// If socket is ready for reading parse netlink events
+static void handler_rtnl_event(struct uloop_fd *u, unsigned int events)
+{
+ nl_recvmsgs(sock_rtnl_event, nl_cb_rtnl_event);
+}
+
+// Evaluate netlink messages
+static int cb_rtnl_event(struct nl_msg *msg, void *arg)
+{
+ struct nlmsghdr *nh = nlmsg_hdr(msg);
+ struct ifinfomsg *ifi = NLMSG_DATA(nh);
+ struct nlattr *nla[__IFLA_MAX];
+
+ if (nh->nlmsg_type != RTM_DELLINK && nh->nlmsg_type != RTM_NEWLINK)
+ goto out;
+
+ nlmsg_parse(nh, sizeof(*ifi), nla, __IFLA_MAX - 1, NULL);
+ if (!nla[IFLA_IFNAME])
+ goto out;
+
+ struct device *dev = device_get(RTA_DATA(nla[IFLA_IFNAME]), false);
+ if (!dev)
+ goto out;
+
+ dev->ifindex = ifi->ifi_index;
+ device_set_present(dev, (nh->nlmsg_type == RTM_NEWLINK));
+
+out:
+ return 0;