???????? bind() ???????????? netlink socket ?? netlink ? socket ??????????netlink socket ?????????£?
view plaincopy to clipboardprint?
struct sockaddr_nl {
sa_family_t nl_family;
unsigned short nl_pad;
__u32 nl_pid;
__u32 nl_groups;
};
??????? nl_family ????????? AF_NETLINK ???? PF_NETLINK????? nl_pad ??????????????????????? 0????? nl_pid ????????????????? ID???????????????????????????????????? 0??????????????????????? ID????? nl_groups ??????????飬bind ???????????y??????????????????飬???????? 0?????????????????κζ??顣
view plaincopy to clipboardprint?
struct timeval timeout;
memset(&client?? 0?? sizeof(client));
client.nl_family = AF_NETLINK;
client.nl_pid = getpid();
client.nl_groups = 1; /* receive broadcast message*/
????????? bind ?????????? nl_pid ????????????????????? ID???????? netlink socket ?????????????????????????????????? netlink socket ?????????? nl_pid ????????????????????????? nl_pid ?????δ??????? ID?????????????????????????????????????????????????????????????Ρ????? bind ????÷?????£?
????view plaincopy to clipboardprint?
????bind(ntSocket?? (struct sockaddr*)&client?? sizeof(client))
????ntSocket????? socket ???÷??????????????????? client ? struct sockaddr_nl ???????????????????ntSocket????????????????????ntSocket?????????select??????ntSocket??????????????recv???????????????????????????ɡ???????????????C?????????????£?
view plaincopy to clipboardprint?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#define UEVENT_BUFFER_SIZE 2048
int main(void)
{
struct sockaddr_nl client;
struct timeval tv;
int ntSocket?? rcvlen?? ret;
fd_set fds;
int buffersize = 1024;
ntSocket = socket(AF_NETLINK?? SOCK_RAW?? NETLINK_KOBJECT_UEVENT);
memset(&client?? 0?? sizeof(client));
client.nl_family = AF_NETLINK;
client.nl_pid = getpid();
client.nl_groups = 1; /* receive broadcast message*/
setsockopt(ntSocket?? SOL_SOCKET?? SO_RCVBUF?? &buffersize?? sizeof(buffersize));
bind(ntSocket?? (struct sockaddr*)&client?? sizeof(client));
while (1) {
char buf[UEVENT_BUFFER_SIZE] = { 0 };
FD_ZERO(&fds);
FD_SET(ntSocket?? &fds);
tv.tv_sec = 0;
tv.tv_usec = 100 * 1000;
ret = select(ntSocket + 1?? &fds?? NULL?? NULL?? &tv);
if(!(ret > 0 && FD_ISSET(ntSocket?? &fds)))
continue;
/* receive data */
rcvlen = recv(ntSocket?? &buf?? sizeof(buf)?? 0);
if (rcvlen > 0) {
printf("%s "?? buf);
// You can do something here to make the program more perfect!!!
}
}
close(ntSocket);
return 0;
}