Golang ParseMAC示例

说明

golang parsemac示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net

示例#1
文件: core.go 项目: troyxmccall/gogospoofdns

func main() {
	if os.Geteuid() != 0 {
		fmt.Println("gogospoofdns requires root!")
		return
	}

	var dev string = "eno1"

	fmt.Println("Running arp poison")
	routerMac, err := net.ParseMAC("00:1A:6D:38:15:FF")
	routerIP := net.IP{192, 168, 0, 100}
	localMac, err := net.ParseMAC("98:90:96:D5:84:7B")
	localIP := net.IP{192, 168, 0, 9}
	victimMac, err := net.ParseMAC("98:90:96:DC:fB:6A")
	victimIP := net.IP{192, 168, 0, 10}
	/********* end parse all IP's and MAC's relevent for poisoning / spoofing *********/

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	go arpPoison(dev, routerMac, routerIP, localMac, localIP, victimMac, victimIP)

	fmt.Println("Running spoofer")
	spoof(dev)
}

示例#2
文件: core.go 项目: grengojbo/adscore

// Parsing Base64 encode client IP and Mac
func ParseParams(params string) (clientIp pgx.NullString, ipV4 bool, clientMac pgx.NullString) {
	ipV4 = false
	clientIp = pgx.NullString{Valid: false}
	clientMac = pgx.NullString{Valid: false}
	b, err := base64.StdEncoding.DecodeString(params)
	if err != nil {
		// fmt.Println(err.Error())
		umac, err := net.ParseMAC(params)
		if err == nil {
			clientMac = pgx.NullString{String: umac.String(), Valid: true}
		}
		return clientIp, ipV4, clientMac
	}
	s := strings.SplitN(string(b), "|", 2)
	if len(s) != 2 {
		return clientIp, ipV4, clientMac
	}

	clientIp, ipV4 = GetIP(s[0])
	umac, err := net.ParseMAC(s[1])
	if err == nil {
		clientMac = pgx.NullString{String: umac.String(), Valid: true}
	}
	return clientIp, ipV4, clientMac
}

示例#3
文件: layers_test.go 项目: kelixin/go.pkt

func TestPackEthIPv4UDPRaw(t *testing.T) {
	eth_pkt := eth.Make()
	eth_pkt.SrcAddr, _ = net.ParseMAC(hwsrc_str)
	eth_pkt.DstAddr, _ = net.ParseMAC(hwdst_str)

	ip4_pkt := ipv4.Make()
	ip4_pkt.SrcAddr = net.ParseIP(ipsrc_str)
	ip4_pkt.DstAddr = net.ParseIP(ipdst_str)

	udp_pkt := udp.Make()
	udp_pkt.SrcPort = 41562
	udp_pkt.DstPort = 8338

	raw_pkt := raw.Make()
	raw_pkt.Data = []byte("fdg agfh ldfhgk hfdkgh kfjdhsg kshfdgk")

	data, err := layers.Pack(eth_pkt, ip4_pkt, udp_pkt, raw_pkt)
	if err != nil {
		t.Fatalf("Error packing: %s", err)
	}

	if ip4_pkt.GetLength() != 66 {
		t.Fatalf("IPv4 length mismatch: %d", ip4_pkt.GetLength())
	}

	if udp_pkt.GetLength() != 46 {
		t.Fatalf("UDP length mismatch: %d", udp_pkt.GetLength())
	}

	if !bytes.Equal(test_eth_ipv4_udp_raw, data) {
		t.Fatalf("Raw packet mismatch: %x", data)
	}
}

示例#4
文件: layers_test.go 项目: kelixin/go.pkt

func TestPackEthIPv4TCPRaw(t *testing.T) {
	eth_pkt := eth.Make()
	eth_pkt.SrcAddr, _ = net.ParseMAC(hwsrc_str)
	eth_pkt.DstAddr, _ = net.ParseMAC(hwdst_str)

	ip4_pkt := ipv4.Make()
	ip4_pkt.SrcAddr = net.ParseIP(ipsrc_str)
	ip4_pkt.DstAddr = net.ParseIP(ipdst_str)

	tcp_pkt := tcp.Make()
	tcp_pkt.SrcPort = 41562
	tcp_pkt.DstPort = 8338
	tcp_pkt.Flags = tcp.Syn
	tcp_pkt.WindowSize = 8192

	raw_pkt := raw.Make()
	raw_pkt.Data = []byte("fdg agfh ldfhgk hfdkgh kfjdhsg kshfdgk")

	data, err := layers.Pack(eth_pkt, ip4_pkt, tcp_pkt, raw_pkt)
	if err != nil {
		t.Fatalf("Error packing: %s", err)
	}

	if ip4_pkt.GetLength() != 78 {
		t.Fatalf("IPv4 length mismatch: %d", ip4_pkt.GetLength())
	}

	if tcp_pkt.GetLength() != 58 {
		t.Fatalf("TCP length mismatch: %d", tcp_pkt.GetLength())
	}

	if !bytes.Equal(test_eth_ipv4_tcp_raw, data) {
		t.Fatalf("Raw packet mismatch: %x", data)
	}
}

示例#5
文件: util.go 项目: karamsivia/netplugin

// BuildGarpPkt builds a Gratuitous ARP packet
func BuildGarpPkt(ip net.IP, mac net.HardwareAddr, vlanID uint16) *openflow13.PacketOut {

	zMac, _ := net.ParseMAC("00:00:00:00:00:00")
	bMac, _ := net.ParseMAC("FF:FF:FF:FF:FF:FF")

	garpPkt, _ := protocol.NewARP(protocol.Type_Request)
	garpPkt.HWSrc = mac
	garpPkt.IPSrc = ip
	garpPkt.HWDst = zMac
	garpPkt.IPDst = ip

	// Build the ethernet packet
	ethPkt := protocol.NewEthernet()
	ethPkt.VLANID.VID = vlanID
	ethPkt.HWDst = bMac
	ethPkt.HWSrc = mac
	ethPkt.Ethertype = 0x0806
	ethPkt.Data = garpPkt

	// Construct Packet out
	pktOut := openflow13.NewPacketOut()
	pktOut.Data = ethPkt

	return pktOut
}

示例#6
文件: ofnet_arp_test.go 项目: jojimt/ofnet

// injectArpReq injects an ARP request into ofnet
func injectArpReq(ofa *OfnetAgent, inPort, vlan int, macSrc, macDst, ipSrc, ipDst string) error {
	if macDst == "" {
		macDst = "ff:ff:ff:ff:ff:ff"
	}

	// inject an ARP request from ep1 for ep2
	arpReq := openflow13.NewPacketIn()
	arpReq.Match.Type = openflow13.MatchType_OXM
	arpReq.Match.AddField(*openflow13.NewInPortField(uint32(inPort)))
	arpReq.Data = *protocol.NewEthernet()
	arpReq.Data.Ethertype = protocol.ARP_MSG
	arpReq.Data.HWDst, _ = net.ParseMAC(macDst)
	arpReq.Data.HWSrc, _ = net.ParseMAC(macSrc)
	if vlan != 0 {
		arpReq.Data.VLANID.VID = uint16(vlan)
	}
	arpPkt, _ := protocol.NewARP(protocol.Type_Request)
	arpPkt.HWSrc, _ = net.ParseMAC(macSrc)
	arpPkt.IPSrc = net.ParseIP(ipSrc)
	arpPkt.HWDst, _ = net.ParseMAC("00:00:00:00:00:00")
	arpPkt.IPDst = net.ParseIP(ipDst)

	arpReq.Data.Data = arpPkt
	pkt := ofctrl.PacketIn(*arpReq)
	ofa.PacketRcvd(ofa.ofSwitch, &pkt)

	log.Debugf("Injected ARP request: %+v\n Packet: %+v", arpPkt, arpReq)
	return nil
}

示例#7
文件: ethernet_test.go 项目: nightrune/ogo

func TestEthUnmarshalBinary(t *testing.T) {
	b := "   00 " + // Delim
		"0a b0 0c 0d e0 0f " + // HWDst
		"00 00 00 00 00 ff " + // HWSrc
		"88 00 " // Ethertype
	b = strings.Replace(b, " ", "", -1)
	byte, _ := hex.DecodeString(b)
	t.Log("Decoded hex string")

	a := New() // Ensure type is set correctly
	a.UnmarshalBinary(byte)
	t.Log("Unmarshaled binary")

	dst, _ := net.ParseMAC("0a:b0:0c:0d:e0:0f")
	src, _ := net.ParseMAC("00:00:00:00:00:ff")

	if int(a.Len()) != (len(byte) - 1) {
		t.Errorf("Got length of %d, expected %d.", a.Len(), (len(byte) - 1))
	} else if a.Ethertype != 0x8800 {
		t.Errorf("Got type %d, expected %d.", a.Ethertype, 0x0880)
	} else if bytes.Compare(a.HWDst, dst) != 0 {
		t.Log("Exp:", dst)
		t.Log("Rec:", a.HWDst)
		t.Errorf("Received length of %d, expected %d", len(a.HWDst), len(dst))
	} else if bytes.Compare(a.HWSrc, src) != 0 {
		t.Log("Exp:", src)
		t.Log("Rec:", a.HWSrc)
		t.Errorf("Received length of %d, expected %d", len(a.HWSrc), len(src))
	}
}

示例#8
文件: dev_test.go 项目: songgao/ether

func TestWriteFrame(t *testing.T) {
	var (
		ifce *net.Interface
		err  error
		d    Dev
	)
	if ifce, err = net.InterfaceByName(*dev); err != nil {
		t.Fatalf("getting interface error: %v", err)
	}
	d, err = NewDev(ifce, nil)
	if err != nil {
		t.Fatal(err)
	}
	dst, err := net.ParseMAC("ff:ff:ff:ff:ff:ff")
	if err != nil {
		t.Fatal(err)
	}
	src, err := net.ParseMAC("12:34:56:78:9a:bc")
	if err != nil {
		t.Fatal(err)
	}
	var frame ethernet.Frame
	w := func() (err error) {
		(&frame).Prepare(dst, src, ethernet.NotTagged, ethernet.WSMP, 13)
		copy(frame.Payload(), "Hello, World!")
		err = d.Write(frame)
		if err != nil {
			return
		}
		return
	}
	for i := 0; i < 16; i++ {
		if nil != w() {
			t.Fatal(err)
		}
	}

	(&frame).Resize(d.Interface().MTU)
	if err = d.Write(frame); err != nil {
		t.Fatalf("writing frame with payload size equal to MTU fails: %v", err)
	}

	(&frame).Resize(d.Interface().MTU + 1)
	if nil == d.Write(frame) {
		t.Fatalf("writing frame with payload larger than MTU does not fail")
	}

	err = d.Close()
	if err != nil {
		t.Fatal(err)
	}

	if err = w(); nil == err {
		t.Fatal("closed Dev can still write")
	}
}

示例#9
文件: vlrouter.go 项目: nikolayvoronchikhin/netplugin

// initialize Fgraph on the switch
func (self *Vlrouter) initFgraph() error {
	sw := self.ofSwitch

	// Create all tables
	self.inputTable = sw.DefaultTable()
	self.vlanTable, _ = sw.NewTable(VLAN_TBL_ID)
	self.ipTable, _ = sw.NewTable(IP_TBL_ID)

	//Create all drop entries
	// Drop mcast source mac
	bcastMac, _ := net.ParseMAC("01:00:00:00:00:00")
	bcastSrcFlow, _ := self.inputTable.NewFlow(ofctrl.FlowMatch{
		Priority:  FLOW_MATCH_PRIORITY,
		MacSa:     &bcastMac,
		MacSaMask: &bcastMac,
	})
	bcastSrcFlow.Next(sw.DropAction())

	// Redirect ARP packets to controller
	arpFlow, _ := self.inputTable.NewFlow(ofctrl.FlowMatch{
		Priority:  FLOW_MATCH_PRIORITY,
		Ethertype: 0x0806,
	})
	arpFlow.Next(sw.SendToController())

	//All ARP replies will need IP table lookup
	Mac, _ := net.ParseMAC("00:00:11:11:11:11")
	arpFlow, _ = self.inputTable.NewFlow(ofctrl.FlowMatch{
		Priority:  300,
		Ethertype: 0x0806,
		MacSa:     &Mac,
	})
	arpFlow.Next(self.ipTable)

	// Send all valid packets to vlan table
	// This is installed at lower priority so that all packets that miss above
	// flows will match entry
	validPktFlow, _ := self.inputTable.NewFlow(ofctrl.FlowMatch{
		Priority: FLOW_MISS_PRIORITY,
	})
	validPktFlow.Next(self.vlanTable)

	// Drop all packets that miss Vlan lookup
	vlanMissFlow, _ := self.vlanTable.NewFlow(ofctrl.FlowMatch{
		Priority: FLOW_MISS_PRIORITY,
	})
	vlanMissFlow.Next(sw.DropAction())

	// Drop all packets that miss IP lookup
	ipMissFlow, _ := self.ipTable.NewFlow(ofctrl.FlowMatch{
		Priority: FLOW_MISS_PRIORITY,
	})
	ipMissFlow.Next(sw.DropAction())

	return nil
}

示例#10
文件: pkt_test.go 项目: kelixin/go.pkt

func MakeTestSimple() *eth.Packet {
	hwsrc, _ := net.ParseMAC(hwsrc_str)
	hwdst, _ := net.ParseMAC(hwdst_str)

	return ð.Packet{
		SrcAddr: hwsrc,
		DstAddr: hwdst,
		Type:    eth.IPv4,
	}
}

示例#11
文件: hash.go 项目: nplanel/skydive

func (fl *FlowLayer) Hash() []byte {
	if fl == nil {
		return []byte{}
	}
	if fl.Protocol == FlowProtocol_ETHERNET {
		amac, err := net.ParseMAC(fl.A)
		if err != nil {
			panic(err)
		}
		bmac, err := net.ParseMAC(fl.B)
		if err != nil {
			panic(err)
		}
		return HashFromValues(amac, bmac)
	}
	if fl.Protocol == FlowProtocol_IPV4 || fl.Protocol == FlowProtocol_IPV6 {
		aip := net.ParseIP(fl.A)
		bip := net.ParseIP(fl.B)
		return HashFromValues(aip, bip)
	}
	if fl.Protocol == FlowProtocol_TCPPORT {
		aTCPPort, err := strconv.ParseUint(fl.A, 10, 16)
		if err != nil {
			panic(err)
		}
		bTCPPort, err := strconv.ParseUint(fl.B, 10, 16)
		if err != nil {
			panic(err)
		}
		return HashFromValues(layers.TCPPort(aTCPPort), layers.TCPPort(bTCPPort))
	}
	if fl.Protocol == FlowProtocol_UDPPORT {
		aUDPPort, err := strconv.ParseUint(fl.A, 10, 16)
		if err != nil {
			panic(err)
		}
		bUDPPort, err := strconv.ParseUint(fl.B, 10, 16)
		if err != nil {
			panic(err)
		}
		return HashFromValues(layers.UDPPort(aUDPPort), layers.UDPPort(bUDPPort))
	}
	if fl.Protocol == FlowProtocol_SCTPPORT {
		aSCTPPort, err := strconv.ParseUint(fl.A, 10, 16)
		if err != nil {
			panic(err)
		}
		bSCTPPort, err := strconv.ParseUint(fl.B, 10, 16)
		if err != nil {
			panic(err)
		}
		return HashFromValues(layers.SCTPPort(aSCTPPort), layers.SCTPPort(bSCTPPort))
	}
	return nil
}

示例#12
文件: main.go 项目: kelixin/go.pkt

func main() {
	log.SetFlags(0)

	usage := `Usage: arp <addr>

Resolve the given IP address using ARP.`

	args, err := docopt.Parse(usage, nil, true, "", false)
	if err != nil {
		log.Fatalf("Invalid arguments: %s", err)
	}

	addr := args["<addr>"].(string)
	addr_ip := net.ParseIP(addr)
	timeout := 5 * time.Second

	route, err := routing.RouteTo(addr_ip)
	if err != nil {
		log.Fatalf("Error: %s", err)
	}

	if route == nil {
		log.Println("No route found")
	}

	c, err := pcap.Open(route.Iface.Name)
	if err != nil {
		log.Fatalf("Error opening interface: %s", err)
	}
	defer c.Close()

	err = c.Activate()
	if err != nil {
		log.Fatalf("Error activating source: %s", err)
	}

	eth_pkt := eth.Make()
	eth_pkt.SrcAddr = route.Iface.HardwareAddr
	eth_pkt.DstAddr, _ = net.ParseMAC("ff:ff:ff:ff:ff:ff")

	arp_pkt := arp.Make()
	arp_pkt.HWSrcAddr = route.Iface.HardwareAddr
	arp_pkt.HWDstAddr, _ = net.ParseMAC("00:00:00:00:00:00")
	arp_pkt.ProtoSrcAddr, _ = route.GetIfaceIPv4Addr()
	arp_pkt.ProtoDstAddr = addr_ip

	pkt, err := network.SendRecv(c, timeout, eth_pkt, arp_pkt)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(pkt.Payload().(*arp.Packet).HWSrcAddr)
}

示例#13
文件: callback_test.go 项目: dereulenspiegel/wifidetector

func TestIsUniqueFunction(t *testing.T) {
	assert := assert.New(t)

	uniqueMac, err := net.ParseMAC("ca:cf:1a:8b:9b:d5")
	assert.Nil(err)
	assert.False(isUnique(uniqueMac))

	nonuniqueMac, err := net.ParseMAC("00:00:00:ea:95:ee")
	assert.Nil(err)
	assert.True(isUnique(nonuniqueMac))

}

示例#14
文件: network.go 项目: hooklift/govix

// NetworkAdapters lists current network adapters attached to the virtual
// machine.
func (v *VM) NetworkAdapters() ([]*NetworkAdapter, error) {
	vmxPath, err := v.VmxPath()
	if err != nil {
		return nil, err
	}

	vmx, err := readVmx(vmxPath)
	if err != nil {
		return nil, err
	}

	var adapters []*NetworkAdapter
	// VMX ethernet adapters seem to not be zero based
	for i := 1; i <= v.totalNetworkAdapters(vmx); i++ {
		id := strconv.Itoa(i)
		prefix := "ethernet" + id

		if vmx[prefix+".present"] == "FALSE" {
			continue
		}

		wakeOnPckRcv, _ := strconv.ParseBool(vmx[prefix+".wakeOnPcktRcv"])
		lnkStateProp, _ := strconv.ParseBool(vmx[prefix+".linkStatePropagation.enable"])
		present, _ := strconv.ParseBool(vmx[prefix+".present"])
		startConnected, _ := strconv.ParseBool(vmx[prefix+".startConnected"])
		address, _ := net.ParseMAC(vmx[prefix+".address"])
		genAddress, _ := net.ParseMAC(vmx[prefix+".generatedAddress"])
		vswitch, _ := GetVSwitch(vmx[prefix+".vnet"])

		adapter := &NetworkAdapter{
			ID:                        id,
			present:                   present,
			ConnType:                  NetworkType(vmx[prefix+".connectionType"]),
			Vdevice:                   VNetDevice(vmx[prefix+".virtualDev"]),
			WakeOnPcktRcv:             wakeOnPckRcv,
			LinkStatePropagation:      lnkStateProp,
			MacAddrType:               MacAddressType(vmx[prefix+".addressType"]),
			MacAddress:                address,
			VSwitch:                   vswitch,
			StartConnected:            startConnected,
			GeneratedMacAddress:       genAddress,
			GeneratedMacAddressOffset: vmx[prefix+".generatedAddressOffset"],
			PciSlotNumber:             vmx[prefix+".pciSlotNumber"],
		}

		adapters = append(adapters, adapter)
	}

	return adapters, nil
}

示例#15
文件: main.go 项目: razc411/DNSMangler

/*
    FUNCTION: arpPoison(targetMAC, gateway, gatewayMAC string){
    RETURNS: Nothing
    ARGUMENTS:
                string targetMAC - the victim mac address for spoofing
								string gateway - the gateway IP the victim uses
								string gatewayMAC - the mac address of the gateway the vicitim uses

    ABOUT:
    Performs arp poisoning of the target machine. Sets its traffic to all come
		through the host machine, and sets the gateway to redirect its traffic for the victim to this host.
*/
func arpPoison(targetMAC, gateway, gatewayMAC string) {

	// i lost my mind over this, the parseip function is broke and adds a bucket of worthless
	// bytes to the beginning of the array, I wish I did this in C
	// I GUESS I DID C
	gw := (net.ParseIP(gateway))[12:]
	tg := (net.ParseIP(target))[12:]
	tgm, _ := net.ParseMAC(targetMAC)
	gwm, _ := net.ParseMAC(gatewayMAC)

	fmt.Print("========================")
	fmt.Printf("GateWay IP:%s\nTarget IP:%s\nGateway MAC:%s\nTarget MAC:%s\n", gateway, target, gatewayMAC, targetMAC)
	fmt.Print("========================")

	ethernetPacket := layers.Ethernet{}
	ethernetPacket.DstMAC = tgm
	ethernetPacket.SrcMAC = macAddr
	ethernetPacket.EthernetType = layers.EthernetTypeARP

	arpPacket := layers.ARP{}
	arpPacket.AddrType = layers.LinkTypeEthernet
	arpPacket.Protocol = 0x0800
	arpPacket.HwAddressSize = 6
	arpPacket.ProtAddressSize = 4
	arpPacket.Operation = 2

	//poison the target
	arpPacket.SourceHwAddress = macAddr
	arpPacket.SourceProtAddress = gw
	arpPacket.DstHwAddress = tgm
	arpPacket.DstProtAddress = tg

	gwEthernetPacket := ethernetPacket
	gwARPPacket := arpPacket

	//poison the gateway
	gwARPPacket.SourceProtAddress = tg
	gwARPPacket.DstHwAddress = gwm
	gwARPPacket.DstProtAddress = gw

	for {
		//poison target
		writePoison(arpPacket, ethernetPacket)
		time.Sleep(1 * time.Second)
		//poison gateway
		writePoison(gwARPPacket, gwEthernetPacket)
		time.Sleep(5 * time.Second)
	}

}

示例#16
文件: filter_test.go 项目: kor44/gofilter

func TestFilterApplyMac(t *testing.T) {
	// compare contains
	f, err := NewFilter("f_mac contains 23:45")
	if err != nil {
		t.Fatal(err)
	}
	h1, _ := net.ParseMAC("01:23:45:67:89:ab:cd:ef")
	if !f.Apply(map[string]interface{}{"f_mac": h1}) {
		t.Error("Packet must pass")
	}
	h2, _ := net.ParseMAC("01:23:44:67:89:ab:cd:ef1")
	if f.Apply(map[string]interface{}{"f_mac": h2}) {
		t.Error("Packet must not pass")
	}
}

示例#17
文件: listen.go 项目: slowteetoe/dashbutton

func main() {
	gatoradeDashButton, _ := net.ParseMAC("74:75:48:a4:59:a8")
	gladDashButton, _ := net.ParseMAC("74:75:48:29:a8:7c")

	flag.Parse()
	log.Printf("Starting up gobot.io features...")

	e := edison.NewEdisonAdaptor("edison")
	// blue led on D4
	led1 := gpio.NewLedDriver(e, "led", "4")
	// red led on D3
	led2 := gpio.NewLedDriver(e, "led", "3")

	e.Connect()
	led1.Start()
	led2.Start()

	log.Printf("Starting up on interface[%v]...", *interfaceName)

	h, err := pcap.OpenLive(*interfaceName, 65536, true, pcap.BlockForever)

	if err != nil || h == nil {
		log.Fatalf("Error opening interface: %s\nPerhaps you need to run as root?\n", err)
	}
	defer h.Close()

	err = h.SetBPFFilter("arp and ((ether src host " + gatoradeDashButton.String() + ") or (ether src host " + gladDashButton.String() + "))")
	if err != nil {
		log.Fatalf("Unable to set filter! %s\n", err)
	}
	log.Println("Listening for Dash buttons...")

	packetSource := gopacket.NewPacketSource(h, h.LinkType())

	// Since we're using a BPF filter to limit packets to only our buttons, we don't need to worry about anything besides MAC here...
	for packet := range packetSource.Packets() {
		ethernetLayer := packet.Layer(layers.LayerTypeEthernet)
		ethernetPacket, _ := ethernetLayer.(*layers.Ethernet)
		if bytes.Equal(ethernetPacket.SrcMAC, gatoradeDashButton) {
			gatoradeButtonPress(led1)
		} else if bytes.Equal(ethernetPacket.SrcMAC, gladDashButton) {
			gladButtonPress(led2)
		} else {
			log.Printf("Received button press, but don't know how to handle MAC[%v]", ethernetPacket.SrcMAC)
		}
	}

}

示例#18
文件: mac.go 项目: nemowen/golang

func main() {
	// 以下读取网卡信息
	Interface, err := net.Interfaces()
	if err != nil {
		panic("未发现网卡地址")
		os.Exit(1)
	}

	handwareAddrs = make(map[string]string, len(Interface))
	for _, inter := range Interface {
		inMAC := strings.ToUpper(inter.HardwareAddr.String())
		handwareAddrs[inMAC] = inMAC
	}

	if len(os.Args) != 2 {
		fmt.Println("为保障安全:请先绑定本机上的网卡地址")
		os.Exit(0)
	}

	addr := os.Args[1]
	h, e := net.ParseMAC(addr)
	if e != nil {
		fmt.Println("为保障安全:请先绑定本机上的网卡地址")
		fmt.Println("方法:client.exe 90-4C-E5-58-7E-FE")
		os.Exit(2)
	}
	inputMAC := strings.ToUpper(h.String())
	if inputMAC != handwareAddrs[inputMAC] {
		fmt.Println("网卡地址不匹配")
		os.Exit(0)
	}
}

示例#19
文件: ov_serf.go 项目: previousnext/kube-ingress

func (d *driver) resolvePeer(nid string, peerIP net.IP) (net.HardwareAddr, net.IPMask, net.IP, error) {
	qPayload := fmt.Sprintf("%s %s", string(nid), peerIP.String())
	resp, err := d.serfInstance.Query("peerlookup", []byte(qPayload), nil)
	if err != nil {
		return nil, nil, nil, fmt.Errorf("resolving peer by querying the cluster failed: %v", err)
	}

	respCh := resp.ResponseCh()
	select {
	case r := <-respCh:
		var macStr, maskStr, vtepStr string
		if _, err := fmt.Sscan(string(r.Payload), &macStr, &maskStr, &vtepStr); err != nil {
			return nil, nil, nil, fmt.Errorf("bad response %q for the resolve query: %v", string(r.Payload), err)
		}

		mac, err := net.ParseMAC(macStr)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("failed to parse mac: %v", err)
		}

		return mac, net.IPMask(net.ParseIP(maskStr).To4()), net.ParseIP(vtepStr), nil

	case <-time.After(time.Second):
		return nil, nil, nil, fmt.Errorf("timed out resolving peer by querying the cluster")
	}
}

示例#20
文件: types_test.go 项目: AlexisBruemmer/juju

func mustParseMAC(value string) net.HardwareAddr {
	parsedMAC, err := net.ParseMAC(value)
	if err != nil {
		panic(fmt.Sprintf("cannot parse MAC %q: %v", value, err))
	}
	return parsedMAC
}

示例#21
文件: netlink_linux.go 项目: MohamedFAhmed/heapster

func SetMacAddress(name, addr string) error {
	if len(name) >= IFNAMSIZ {
		return fmt.Errorf("Interface name %s too long", name)
	}

	hw, err := net.ParseMAC(addr)
	if err != nil {
		return err
	}

	s, err := getIfSocket()
	if err != nil {
		return err
	}
	defer syscall.Close(s)

	ifr := ifreqHwaddr{}
	ifr.IfruHwaddr.Family = syscall.ARPHRD_ETHER
	copy(ifr.IfrnName[:len(ifr.IfrnName)-1], name)

	for i := 0; i < 6; i++ {
		ifr.IfruHwaddr.Data[i] = ifrDataByte(hw[i])
	}

	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), syscall.SIOCSIFHWADDR, uintptr(unsafe.Pointer(&ifr))); err != 0 {
		return err
	}
	return nil
}

示例#22
文件: machine_linklayerdevices.go 项目: makyo/juju

func (m *Machine) validateSetLinkLayerDeviceArgs(args *LinkLayerDeviceArgs) error {
	if args.Name == "" {
		return errors.NotValidf("empty Name")
	}
	if !IsValidLinkLayerDeviceName(args.Name) {
		logger.Warningf(
			"link-layer device %q on machine %q has invalid name (using anyway)",
			args.Name, m.Id(),
		)
	}

	if args.ParentName != "" {
		if err := m.validateLinkLayerDeviceParent(args); err != nil {
			return errors.Trace(err)
		}
	}

	if !IsValidLinkLayerDeviceType(string(args.Type)) {
		return errors.NotValidf("Type %q", args.Type)
	}

	if args.MACAddress != "" {
		if _, err := net.ParseMAC(args.MACAddress); err != nil {
			return errors.NotValidf("MACAddress %q", args.MACAddress)
		}
	}
	return nil
}

示例#23
文件: driver_test.go 项目: YujiOshima/libnetwork

func (test *testEndpoint) MacAddress() net.HardwareAddr {
	if test.macAddress == "" {
		return nil
	}
	mac, _ := net.ParseMAC(test.macAddress)
	return mac
}

示例#24

func (ep *endpoint) UnmarshalJSON(value []byte) error {
	var (
		err   error
		epMap map[string]interface{}
	)

	json.Unmarshal(value, &epMap)

	ep.id = epMap["id"].(string)
	ep.nid = epMap["nid"].(string)
	if v, ok := epMap["mac"]; ok {
		if ep.mac, err = net.ParseMAC(v.(string)); err != nil {
			return types.InternalErrorf("failed to decode endpoint interface mac address after json unmarshal: %s", v.(string))
		}
	}
	if v, ok := epMap["addr"]; ok {
		if ep.addr, err = types.ParseCIDR(v.(string)); err != nil {
			return types.InternalErrorf("failed to decode endpoint interface ipv4 address after json unmarshal: %v", err)
		}
	}
	if v, ok := epMap["ifName"]; ok {
		ep.ifName = v.(string)
	}

	return nil
}

示例#25
文件: driver.go 项目: xytis/polyp

func (i *ipam) RequestAddress(rq *ipamapi.RequestAddressRequest) (res *ipamapi.RequestAddressResponse, err error) {
	Log.Debugln("RequestAddress %v", rq)
	defer func() { Log.Debugln("RequestAddress returned res: %v, err: %v", res, err) }()
	options := rq.Options
	macAddr, err := net.ParseMAC(options[netlabel.MacAddress])
	if err != nil {
		err = fmt.Errorf("Mac address not understood %v", options[netlabel.MacAddress])
		return
	}
	parts := strings.Split(rq.PoolID, "-")
	if len(parts) != 3 || parts[0] != PoolName {
		err = fmt.Errorf("Unrecognized pool ID: %s", rq.PoolID)
		return
	}
	var subnet, iprange *net.IPNet
	if _, subnet, err = net.ParseCIDR(parts[1]); err != nil {
		return
	}
	if _, iprange, err = net.ParseCIDR(parts[2]); err != nil {
		return
	}
	Log.Debugf("We should query DHCP with: mac %v, subnet %v, iprange %v", macAddr, subnet, iprange)
	res = &ipamapi.RequestAddressResponse{
		Address: "172.13.0.84/24",
		Data: map[string]string{
			"ohay": "Good day to you too, sir!",
		},
	}
	return
}

示例#26
文件: ovsSwitch.go 项目: balajisiva/netplugin

// UpdatePort updates an OVS port without creating it
func (sw *OvsSwitch) UpdatePort(intfName string, cfgEp *OvsCfgEndpointState, pktTag int) error {
	// Get OVS port name
	ovsPortName := getOvsPostName(intfName)

	// Add the endpoint to ofnet
	if sw.netType == "vxlan" {
		// Get the openflow port number for the interface
		ofpPort, err := sw.ovsdbDriver.GetOfpPortNo(ovsPortName)
		if err != nil {
			log.Errorf("Could not find the OVS port %s. Err: %v", ovsPortName, err)
			return err
		}

		macAddr, _ := net.ParseMAC(cfgEp.MacAddress)

		// Build the endpoint info
		endpoint := ofnet.EndpointInfo{
			PortNo:  ofpPort,
			MacAddr: macAddr,
			Vlan:    uint16(pktTag),
			IpAddr:  net.ParseIP(cfgEp.IPAddress),
		}

		// Add the local port to ofnet
		err = sw.ofnetAgent.AddLocalEndpoint(endpoint)
		if err != nil {
			log.Errorf("Error adding local port %s to ofnet. Err: %v", ovsPortName, err)
			return err
		}
	}

	return nil
}

示例#27
文件: vxlanBridge.go 项目: shwethab/netplugin

// Mac route add rpc call from master
func (self *Vxlan) MacRouteAdd(macRoute *MacRoute, ret *bool) error {
	log.Infof("Received mac route: %+v", macRoute)

	// If this is a local route we are done
	if macRoute.OriginatorIp.String() == self.agent.localIp.String() {
		return nil
	}

	// Check if we have the route already and which is more recent
	oldRoute := self.macRouteDb[macRoute.MacAddrStr]
	if oldRoute != nil {
		// If old route has more recent timestamp, nothing to do
		if !macRoute.Timestamp.After(oldRoute.Timestamp) {
			return nil
		}
	}

	// First, add the route to local routing table
	self.macRouteDb[macRoute.MacAddrStr] = macRoute

	// Lookup the VTEP for the route
	vtepPort := self.agent.vtepTable[macRoute.OriginatorIp.String()]
	if vtepPort == nil {
		log.Errorf("Could not find the VTEP for mac route: %+v", macRoute)

		return errors.New("VTEP not found")
	}

	// map VNI to vlan Id
	vlanId := self.agent.vniVlanMap[macRoute.Vni]
	if vlanId == nil {
		log.Errorf("Macroute %+v on unknown VNI: %d", macRoute, macRoute.Vni)
		return errors.New("Unknown VNI")
	}

	macAddr, _ := net.ParseMAC(macRoute.MacAddrStr)

	// Install the route in OVS
	// Create an output port for the vtep
	outPort, err := self.ofSwitch.OutputPort(*vtepPort)
	if err != nil {
		log.Errorf("Error creating output port %d. Err: %v", *vtepPort, err)
		return err
	}

	// Finally install the mac address
	macFlow, _ := self.macDestTable.NewFlow(ofctrl.FlowMatch{
		Priority: FLOW_MATCH_PRIORITY,
		VlanId:   *vlanId,
		MacDa:    &macAddr,
	})
	macFlow.PopVlan()
	macFlow.SetTunnelId(uint64(macRoute.Vni))
	macFlow.Next(outPort)

	// Save the flow in DB
	self.macFlowDb[macRoute.MacAddrStr] = macFlow

	return nil
}

示例#28
文件: p2p.go 项目: subutai-io/p2p

// HandleXpeerPingMessage receives a cross-peer ping message
func (p *PeerToPeer) HandleXpeerPingMessage(msg *P2PMessage, srcAddr *net.UDPAddr) {
	pt := PingType(msg.Header.NetProto)
	if pt == PingReq {
		Log(Debug, "Ping request received")
		// Send a PING response
		r := CreateXpeerPingMessage(PingResp, p.HardwareAddr.String())
		addr, err := net.ParseMAC(string(msg.Data))
		if err != nil {
			Log(Error, "Failed to parse MAC address in crosspeer ping message")
		} else {
			p.SendTo(addr, r)
			Log(Debug, "Sending to %s", addr.String())
		}
	} else {
		Log(Debug, "Ping response received")
		// Handle PING response
		for i, peer := range p.NetworkPeers {
			if peer.PeerHW.String() == string(msg.Data) {
				peer.PingCount = 0
				peer.LastContact = time.Now()
				p.PeersLock.Lock()
				p.NetworkPeers[i] = peer
				p.PeersLock.Unlock()
				runtime.Gosched()
			}
		}
	}
}

示例#29
文件: opts.go 项目: frewsxcv/empire

func ValidateMACAddress(val string) (string, error) {
	_, err := net.ParseMAC(strings.TrimSpace(val))
	if err != nil {
		return "", err
	}
	return val, nil
}

示例#30
文件: etcd_datasource.go 项目: colonelmo/blacksmith

// Machines returns an array of the recognized machines in etcd datasource
// part of GeneralDataSource interface implementation
func (ds *EtcdDataSource) Machines() ([]Machine, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	response, err := ds.keysAPI.Get(ctx, ds.prefixify("/machines"), &etcd.GetOptions{Recursive: false})
	if err != nil {
		return nil, err
	}
	ret := make([]Machine, 0)
	for _, ent := range response.Node.Nodes {
		pathToMachineDir := ent.Key
		machineName := pathToMachineDir[strings.LastIndex(pathToMachineDir, "/")+1:]
		macStr := macFromName(machineName)
		macAddr, err := net.ParseMAC(macStr)
		if err != nil {
			return nil, err
		}
		machine, exist := ds.GetMachine(macAddr)
		if !exist {
			return nil, errors.New("Inconsistent datasource")
		}
		ret = append(ret, machine)
	}
	return ret, nil
}

展开阅读全文