代码如下 (main.go):
package main
import (
"flag"
"fmt"
"net"
"strings"
)
const IPV4 = 4
const IPV6 = 6
func getIPType(ip string) int {for i := 0; i < len(ip); i++ {switch ip[i] {
case '.':
return IPV4
case ':':
return IPV6
}
}
return 0
}
func main() {
// Define flags
macPtr := flag.String("mac", "","MAC address")
sipPtr := flag.String("sip", "","Source IP address")
dipPtr := flag.String("dip", "","Destination IP address")
vlanidPtr := flag.Int("vlanid", -1, "VLAN ID")
intfNamePtr := flag.String("intf_name", "","Interface name")
// Parse flags
flag.Parse()
// Check if all flags are provided
if *macPtr == ""|| *sipPtr =="" || *dipPtr == ""|| *vlanidPtr == 0 || *intfNamePtr =="" {fmt.Println("Usage: go run check.go -mac <mac> -sip <sip> -dip <dip> -vlanid <vlanid> -intf_name <intf_name>")
return
}
// Check if the VLAN ID is valid
if *vlanidPtr < 1 || *vlanidPtr > 4095 {fmt.Println("Invalid VLAN ID")
return
}
// Check if the interface name is valid
if len(*intfNamePtr) > 100 {fmt.Println("Interface name is too long")
return
}
// Parse the MAC address
mac, err := net.ParseMAC(*macPtr)
if err != nil {fmt.Println("Invalid MAC address")
return
}
// Check if the source IP address and destination IP address are of the same type
if getIPType(*sipPtr) != getIPType(*dipPtr) {fmt.Println("Both source and destination IP addresses must be of the same type IPv4/IPv6")
return
}
// Parse the source IP address
sip := net.ParseIP(*sipPtr)
if sip == nil {fmt.Println("Invalid source IP address")
return
}
// Parse the destination IP address
dip := net.ParseIP(*dipPtr)
if dip == nil {fmt.Println("Invalid destination IP address")
return
}
//Print the validated arguments
fmt.Printf("MAC address: %s\n", mac)
fmt.Printf("Source IP address: %s\n", sip)
fmt.Printf("Destination IP address: %s\n", dip)
fmt.Printf("VLAN ID: %d\n", *vlanidPtr)
fmt.Printf("Interface name: %s\n", strings.TrimSpace(*intfNamePtr))
}
编译:
go build -o check main.go
执行
% ./check --help
Usage of ./check:
-dip string
Destination IP address
-intf_name string
Interface name
-mac string
MAC address
-sip string
Source IP address
-vlanid int
VLAN ID (default -1)
./check -mac A1:2B:C3:4D:E5:6F -sip 192.168.1.1 -dip 127.0.0.1 -intf_name abc -vlanid 10
MAC address: a1:2b:c3:4d:e5:6f
Source IP address: 192.168.1.1
Destination IP address: 127.0.0.1
VLAN ID: 10
Interface name: abc