读取一个TCPDump文件的包头并打印出来。用到了os.Open()、os.CLose()打开关闭文件。用到bufio.reader.read()读取数据到byte数组。
Go语言貌似不会自动转型,所以byte移位前要强制转型。
package main
import (
"fmt"
"os"
"bufio"
)
func parseTCPDumpHeader(h[] byte){
var magic uint32 = uint32(h[3])<<24 | uint32(h[2])<<16 | uint32(h[1])<<8 | uint32(h[0]);
var major uint16 = uint16(h[5])<<8 | uint16(h[4]);
var minor uint16 = uint16(h[7])<<24 | uint16(h[6]);
fmt.Printf("magic: 0x%x, major: %x, minor: %x\r\n", magic, major, minor);
}
func main() {
fmt.Printf("Hello, %s!\r\n", "World")
var f, err = os.Open("./1.cap")
defer f.Close();
if (err!=nil) {
fmt.Printf("Open file failed.\r\n");
}
//var tcpDumpHeader = [4]byte;
var reader = bufio.NewReader(f)
var tcpDumpHeader = make([]byte, 24);
fmt.Printf("len: %d\r\n", len(tcpDumpHeader));
var n, err2 = reader.Read(tcpDumpHeader)
if (err2!=nil){
fmt.Printf("Read file error.\r\n");
}
if(n== len(tcpDumpHeader)) {
parseTCPDumpHeader(tcpDumpHeader)
}
}