+#define nl80211_handle_alloc nl_socket_alloc_cb
+#define nl80211_handle_destroy nl_socket_free
+#else
+/*
+ * libnl 1.1 has a bug, it tries to allocate socket numbers densely
+ * but when you free a socket again it will mess up its bitmap and
+ * and use the wrong number the next time it needs a socket ID.
+ * Therefore, we wrap the handle alloc/destroy and add our own pid
+ * accounting.
+ */
+static uint32_t port_bitmap[32] = { 0 };
+
+static struct nl_handle *nl80211_handle_alloc(void *cb)
+{
+ struct nl_handle *handle;
+ uint32_t pid = getpid() & 0x3FFFFF;
+ int i;
+
+ handle = nl_handle_alloc_cb(cb);
+
+ for (i = 0; i < 1024; i++) {
+ if (port_bitmap[i / 32] & (1 << (i % 32)))
+ continue;
+ port_bitmap[i / 32] |= 1 << (i % 32);
+ pid += i << 22;
+ break;
+ }
+
+ nl_socket_set_local_port(handle, pid);
+
+ return handle;
+}
+
+static void nl80211_handle_destroy(struct nl_handle *handle)
+{
+ uint32_t port = nl_socket_get_local_port(handle);
+
+ port >>= 22;
+ port_bitmap[port / 32] &= ~(1 << (port % 32));
+
+ nl_handle_destroy(handle);
+}