#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/un.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/types.h>
#include <linux/netlink.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define UEVENT_BUFFER_SIZE 2048
static int init_hotplug_sock()
{
const int i_buffersize = 1024;
int i_ret = 0;
struct sockaddr_nl saddr_nl;
bzero( &saddr_nl, sizeof( struct sockaddr_nl ) );
saddr_nl.nl_family = AF_NETLINK;
saddr_nl.nl_pid = getpid();
saddr_nl.nl_groups = 1;
int i_sock = socket( PF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT );
if ( -1 == i_sock )
{
perror( "socket" );
return -1;
}
setsockopt( i_sock, SOL_SOCKET, SO_RCVBUF, &i_buffersize, sizeof( i_buffersize ) );
i_ret = bind( i_sock, ( struct sockaddr * )&saddr_nl, sizeof( struct sockaddr_nl ) );
if (i_ret < 0)
{
perror("bind");
close(i_sock);
return -1;
}
return i_sock;
}
int main(int argc, char* argv[])
{
int i_rcvlen = 0;
int i_hotplug_sock = init_hotplug_sock();
if ( i_hotplug_sock < 0 )
return -1;
while(1)
{
/* Netlink message buffer */
char psz_buf[UEVENT_BUFFER_SIZE * 2] = {0};
i_rcvlen = recv(i_hotplug_sock, &psz_buf, sizeof(psz_buf), 0);
if ( i_rcvlen > 0 )
{
printf( "recv msg: %s, length: %d\n", psz_buf, strlen( psz_buf ) );
/* USB 设备的插拔会出现字符信息,通过比较不同的信息确定特定设备的插拔,在这添加比较代码 */
}
}
return 0;
}