Created
February 23, 2020 13:51
-
-
Save XoneStar/74d1eeedada222e60e64ee2545d0bf3f to your computer and use it in GitHub Desktop.
go netlink monitor usb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"golang.org/x/sys/unix" | |
) | |
func main() { | |
fd, err := unix.Socket( | |
// Always used when opening netlink sockets. | |
unix.AF_NETLINK, | |
// Seemingly used interchangeably with SOCK_DGRAM, | |
// but it appears not to matter which is used. | |
unix.SOCK_RAW, | |
// The netlink family that the socket will communicate | |
// with, such as NETLINK_ROUTE or NETLINK_GENERIC. | |
unix.NETLINK_KOBJECT_UEVENT, | |
) | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
err = unix.Bind(fd, &unix.SockaddrNetlink{ | |
// Always used when binding netlink sockets. | |
Family: unix.AF_NETLINK, | |
// A bitmask of multicast groups to join on bind. | |
// Typically set to zero. | |
Groups: 1, | |
// If you'd like, you can assign a PID for this socket | |
// here, but in my experience, it's easier to leave | |
// this set to zero and let netlink assign and manage | |
// PIDs on its own. | |
Pid: 0, | |
}) | |
if err == nil { | |
for { | |
data := make([]byte, 1024) | |
n, _, _ := unix.Recvfrom(fd, data, 0) | |
if n != 0 { | |
if bytes.HasPrefix(data, []byte("remove@/devices/")) || | |
bytes.HasPrefix(data, []byte("add@/devices/")) { | |
bytesArr := bytes.Split(data, []byte(string(0))) | |
var results [][]byte | |
for _, item := range bytesArr { | |
if !bytes.Equal(item, []byte("")) { | |
results = append(results, item) | |
} else { | |
break | |
} | |
} | |
fmt.Println(string(bytes.Join(results, []byte("\n")))) | |
} | |
} | |
} | |
} else { | |
fmt.Println(err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment