You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.3 KiB
49 lines
1.3 KiB
package parser
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"errors"
|
|
"net"
|
|
)
|
|
|
|
// 取值参考自https://en.wikipedia.org/wiki/EtherType,只取常用的ipv4/6和arp类型
|
|
const (
|
|
EthernetTypeIPv4 = 0x0800
|
|
EthernetTypeARP = 0x0806
|
|
EthernetTypeIPv6 = 0x86DD
|
|
)
|
|
|
|
type Ethernet struct {
|
|
BaseLayer
|
|
Source net.HardwareAddr // 源mac
|
|
Destination net.HardwareAddr // 目的mac
|
|
Type uint16 // 网络层协议类型
|
|
}
|
|
|
|
func (e *Ethernet) LayerType() int {
|
|
return LayerTypeEthernet
|
|
}
|
|
|
|
func (e *Ethernet) GetSourceMac() string {
|
|
return e.Source.String()
|
|
}
|
|
|
|
func (e *Ethernet) GetDestinationMac() string {
|
|
return e.Destination.String()
|
|
}
|
|
|
|
func DecodeEthernet(data []byte) (*Ethernet, error) {
|
|
// 帧数据大小小于14,不符合以太网帧格式要求
|
|
if len(data) < 14 {
|
|
return nil, errors.New("[ethernet] 数据包太小,不符合以太网帧格式要求")
|
|
}
|
|
|
|
eth := &Ethernet{}
|
|
eth.Destination = data[:6] // 0~5 byte: 目标mac
|
|
eth.Source = data[6:12] // 6~11 byte: 源mac
|
|
eth.Type = binary.BigEndian.Uint16(data[12:14]) // 12~13 byte: 类型字段,大端序,uint16
|
|
|
|
eth.Header = data[:14]
|
|
eth.Payload = data[14:]
|
|
return eth, nil
|
|
}
|
|
|