代码拉取完成,页面将自动刷新
package fd
import (
"errors"
"fmt"
"golang.org/x/sys/unix"
"time"
"unsafe"
)
type Interface struct {
IfName string
SocketFd int
ifType int32
Interface int32
openTime uint32 // 单位ms, 在linux版本中这个数值与time.Time有间接联系, 不直接相等, 并且size只有4字节, 可能溢出
}
const (
CanFrameWithoutData = 8
CanFrameMaxDlc = 8
CanFdFrameMaxDlc = 64
CanInterfaceMaxBuf = 16
CanFdInterfaceMaxBuf = 72
)
// 从can-utils里看到的定义
const (
_ = iota
CAN_RAW_FILTER /* set 0 .. n can_filter(s) */
CAN_RAW_ERR_FILTER /* set filter for error frames */
CAN_RAW_LOOPBACK /* local loopback (default:on) */
CAN_RAW_RECV_OWN_MSGS /* receive my own msgs (default:off) */
CAN_RAW_FD_FRAMES /* allow CAN FD frames (default:off) */
CAN_RAW_JOIN_FILTERS /* all filters must match to trigger */
)
/* 从can-utils里看到的定义, 可以在unix包里找到: particular protocols of the protocol family PF_CAN */
const (
_ = iota
CAN_RAW /* RAW sockets */
CAN_BCM /* Broadcast Manager */
CAN_TP16 /* VAG Transport Protocol v1.6 */
CAN_TP20 /* VAG Transport Protocol v2.0 */
CAN_MCNET /* Bosch MCNet */
CAN_ISOTP /* ISO 15765-2 Transport Protocol */
CAN_J1939 /* SAE J1939 */
CAN_NPROTO
)
const (
IF_TYPE_RAW_FD = iota
IF_TYPE_ISOTP
)
const (
SOL_CAN_BASE = 100
SOL_CAN_RAW = 101
)
func getIfIndex(fd int, ifName string) (int, error) {
ifNameRaw, err := unix.ByteSliceFromString(ifName)
if err != nil {
return 0, err
}
if len(ifNameRaw) > 16 {
return 0, errors.New("maximum ifname length is 16 characters")
}
ifReq := ifreqIndex{}
copy(ifReq.Name[:], ifNameRaw)
err = ioctlIfreq(fd, &ifReq)
return ifReq.Index, err
}
type ifreqIndex struct {
Name [16]byte
Index int
}
func ioctlIfreq(fd int, ifreq *ifreqIndex) (err error) {
_, _, errno := unix.Syscall(
unix.SYS_IOCTL,
uintptr(fd),
unix.SIOCGIFINDEX,
uintptr(unsafe.Pointer(ifreq)),
)
if errno != 0 {
err = fmt.Errorf("ioctl: %v", errno)
}
return
}
func (i Interface) SetLoopback(enable bool) error {
value := 0
if enable {
value = 1
}
err := unix.SetsockoptInt(i.SocketFd, unix.SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, value)
return err
}
func (i Interface) SetRecvTimeout(timeout time.Duration) error {
tv := unix.NsecToTimeval(timeout.Nanoseconds())
err := unix.SetsockoptTimeval(i.SocketFd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, &tv)
return err
}
func (i Interface) SetSendTimeout(timeout time.Duration) error {
tv := unix.NsecToTimeval(timeout.Nanoseconds())
err := unix.SetsockoptTimeval(i.SocketFd, unix.SOL_SOCKET, unix.SO_SNDTIMEO, &tv)
return err
}
func (i Interface) Close() error {
return unix.Close(i.SocketFd)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。