Golang IPv4示例

说明

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

编程语言: Golang

命名空间/包名称: net

示例#1
文件: stanza_test.go 项目: RubanDeventhiran/coreos-cloudinit

func TestParseInterfaceStanzaStaticPostUp(t *testing.T) {
	options := []string{
		"address 192.168.1.100",
		"netmask 255.255.255.0",
		"post-up route add gw 192.168.1.1 -net 192.168.1.0 netmask 255.255.255.0",
	}
	expect := []route{
		{
			destination: net.IPNet{
				IP:   net.IPv4(192, 168, 1, 0),
				Mask: net.IPv4Mask(255, 255, 255, 0),
			},
			gateway: net.IPv4(192, 168, 1, 1),
		},
	}

	iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, options)
	if err != nil {
		t.FailNow()
	}
	static, ok := iface.configMethod.(configMethodStatic)
	if !ok {
		t.FailNow()
	}
	if !reflect.DeepEqual(static.routes, expect) {
		t.FailNow()
	}
}

示例#2
文件: util_test.go 项目: rw/goser

func newGogopbLog(record *gogopb.Log) {
	record.Timestamp = time.Now().UnixNano()
	record.ZoneId = 123456
	record.ZonePlan = gogopb.ZonePlan_FREE

	record.Http = gogopb.HTTP{
		Protocol:    gogopb.HTTP_HTTP11,
		Status:      200,
		HostStatus:  503,
		UpStatus:    520,
		Method:      gogopb.HTTP_GET,
		ContentType: "text/html",
		UserAgent:   userAgent,
		Referer:     "https://www.cloudflare.com/",
		RequestURI:  "/cdn-cgi/trace",
	}

	record.Origin = gogopb.Origin{
		Ip:       gogopb.IP(net.IPv4(1, 2, 3, 4).To4()),
		Port:     8080,
		Hostname: "www.example.com",
		Protocol: gogopb.Origin_HTTPS,
	}

	record.Country = gogopb.Country_US
	record.CacheStatus = gogopb.CacheStatus_HIT
	record.ServerIp = gogopb.IP(net.IPv4(192, 168, 1, 1).To4())
	record.ServerName = "metal.cloudflare.com"
	record.RemoteIp = gogopb.IP(net.IPv4(10, 1, 2, 3).To4())
	record.BytesDlv = 123456
	record.RayId = "10c73629cce30078-LAX"
}

示例#3
文件: header.go 项目: alisle/elleLog

// ParseHeader parses b as an IPv4 header.
func ParseHeader(b []byte) (*Header, error) {
	if len(b) < HeaderLen {
		return nil, errHeaderTooShort
	}
	hdrlen := (int(b[0]) & 0x0f) << 2
	if hdrlen > len(b) {
		return nil, errBufferTooShort
	}
	h := &Header{}
	h.Version = int(b[0] >> 4)
	h.Len = hdrlen
	h.TOS = int(b[posTOS])
	if supportsNewIPInput {
		h.TotalLen = int(b[posTotalLen])<<8 | int(b[posTotalLen+1])
		h.FragOff = int(b[posFragOff])<<8 | int(b[posFragOff+1])
	} else {
		h.TotalLen = int(*(*uint16)(unsafe.Pointer(&b[posTotalLen : posTotalLen+1][0])))
		h.TotalLen += hdrlen
		h.FragOff = int(*(*uint16)(unsafe.Pointer(&b[posFragOff : posFragOff+1][0])))
	}
	h.ID = int(b[posID])<<8 | int(b[posID+1])
	h.TTL = int(b[posTTL])
	h.Protocol = int(b[posProtocol])
	h.Checksum = int(b[posChecksum])<<8 | int(b[posChecksum+1])
	h.Src = net.IPv4(b[posSrc], b[posSrc+1], b[posSrc+2], b[posSrc+3])
	h.Dst = net.IPv4(b[posDst], b[posDst+1], b[posDst+2], b[posDst+3])
	if hdrlen-HeaderLen > 0 {
		h.Options = make([]byte, hdrlen-HeaderLen)
		copy(h.Options, b[HeaderLen:])
	}
	return h, nil
}

示例#4
文件: roundrobin_test.go 项目: SivagnanamCiena/calico-kubernetes

func TestStickyLoadBalanaceWorksWithMultipleEndpointsStickyNone(t *testing.T) {
	client1 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}
	client2 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 2), Port: 0}
	client3 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 3), Port: 0}
	loadBalancer := NewLoadBalancerRR()
	service := ServicePortName{types.NamespacedName{"testnamespace", "foo"}, ""}
	endpoint, err := loadBalancer.NextEndpoint(service, nil)
	if err == nil || len(endpoint) != 0 {
		t.Errorf("Didn't fail with non-existent service")
	}

	loadBalancer.NewService(service, api.AffinityTypeNone, 0)
	endpoints := make([]api.Endpoints, 1)
	endpoints[0] = api.Endpoints{
		ObjectMeta: api.ObjectMeta{Name: service.Name, Namespace: service.Namespace},
		Subsets: []api.EndpointSubset{
			{
				Addresses: []api.EndpointAddress{{IP: "endpoint"}},
				Ports:     []api.EndpointPort{{Port: 1}, {Port: 2}, {Port: 3}},
			},
		},
	}
	loadBalancer.OnUpdate(endpoints)

	shuffledEndpoints := loadBalancer.services[service].endpoints
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client1)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[2], client2)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client2)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client3)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[2], client3)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client1)
}

示例#5
文件: tcpmap_test.go 项目: linkosmos/redial

func testIPs() (output []net.IP) {
	output = append(output, net.IPv4(127, 0, 1, 2))
	output = append(output, net.IPv4(128, 0, 1, 2))
	output = append(output, net.IPv4(129, 0, 1, 2))
	output = append(output, net.IPv4(130, 0, 1, 2))
	return output
}

示例#6
文件: network_proxy_test.go 项目: 98pm/docker

func TestUDPWriteError(t *testing.T) {
	frontendAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}
	// Hopefully, this port will be free: */
	backendAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 25587}
	proxy, err := NewProxy(frontendAddr, backendAddr)
	if err != nil {
		t.Fatal(err)
	}
	defer proxy.Close()
	go proxy.Run()
	client, err := net.Dial("udp", "127.0.0.1:25587")
	if err != nil {
		t.Fatalf("Can't connect to the proxy: %v", err)
	}
	defer client.Close()
	// Make sure the proxy doesn't stop when there is no actual backend:
	client.Write(testBuf)
	client.Write(testBuf)
	backend := NewEchoServer(t, "udp", "127.0.0.1:25587")
	defer backend.Close()
	backend.Run()
	client.SetDeadline(time.Now().Add(10 * time.Second))
	if _, err = client.Write(testBuf); err != nil {
		t.Fatal(err)
	}
	recvBuf := make([]byte, testBufSize)
	if _, err = client.Read(recvBuf); err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(testBuf, recvBuf) {
		t.Fatal(fmt.Errorf("Expected [%v] but got [%v]", testBuf, recvBuf))
	}
}

示例#7
文件: message.go 项目: vonwenm/GoDHCP

func ReadMessage(c *net.UDPConn) (msg *Message, src net.Addr, err os.Error) {
	buff := make([]byte, DHCP_MAX_LEN)
	//log.Printf("Waiting for read")
	n, src, err := c.ReadFromUDP(buff)
	if err != nil {
		return
	}
	if n < DHCP_MIN_LEN {
		err = os.NewError("Invalid DHCP messge received (too small)")
		return
	}
	buff = buff[0:n]
	msg = &Message{
		Operation:    buff[0],
		HardwareType: buff[1],
		HardwareLen:  buff[2],
		Hops:         buff[3],
		Xid:          binary.LittleEndian.Uint32(buff[4:8]),
		Secs:         binary.LittleEndian.Uint16(buff[8:10]),
		Flags:        binary.LittleEndian.Uint16(buff[10:12]),
		ClientIP:     net.IPv4(buff[12], buff[13], buff[14], buff[15]),
		YourIP:       net.IPv4(buff[16], buff[17], buff[18], buff[19]),
		ServerIP:     net.IPv4(buff[20], buff[21], buff[22], buff[23]),
		GatewayIP:    net.IPv4(buff[24], buff[25], buff[26], buff[27]),
	}
	copy(msg.ClientHWAddr[0:16], buff[28:44])
	// We skip the magic bytes and assume for now.
	msg.Options, err = ParseOptions(buff[DHCP_MIN_LEN+4:])
	//log.Printf("Parsed %d options.", len(msg.Options))
	// TODO: Handle Option 52 extensions.
	return
}

示例#8
文件: fetcher_test.go 项目: joshie/lochness

func TestFetchHypervisors(t *testing.T) {

	// Setup
	f := NewFetcher("http://127.0.0.1:4001")
	defer testhelper.Cleanup(f.etcdClient)

	// Create supporting objects
	n, err := testhelper.NewNetwork(f.context)
	h.Ok(t, err)
	s, err := testhelper.NewSubnet(f.context, "10.10.10.0/24", net.IPv4(10, 10, 10, 1), net.IPv4(10, 10, 10, 10), net.IPv4(10, 10, 10, 250), n)
	h.Ok(t, err)

	// Create two hypervisors
	h1, err := testhelper.NewHypervisor(f.context, "de:ad:be:ef:7f:21", net.IPv4(192, 168, 100, 200), net.IPv4(192, 168, 100, 1), net.IPv4(255, 255, 255, 0), "br0", s)
	h.Ok(t, err)
	h2, err := testhelper.NewHypervisor(f.context, "de:ad:be:ef:7f:23", net.IPv4(192, 168, 100, 203), net.IPv4(192, 168, 100, 1), net.IPv4(255, 255, 255, 0), "br0", s)
	h.Ok(t, err)

	// Fetch and make sure they're present
	hvs, err := f.Hypervisors()
	h.Ok(t, err)
	if _, ok := hvs[h1.ID]; !ok {
		t.Error("Hypervisor #1 is missing from list")
	}
	h.Equals(t, hvs[h1.ID].MAC.String(), "de:ad:be:ef:7f:21")
	if _, ok := hvs[h2.ID]; !ok {
		t.Error("Hypervisor #2 is missing from list")
	}
	h.Equals(t, hvs[h2.ID].MAC.String(), "de:ad:be:ef:7f:23")

}

示例#9
文件: fetcher_test.go 项目: joshie/lochness

func TestFetchSubnets(t *testing.T) {

	// Setup
	f := NewFetcher("http://127.0.0.1:4001")
	defer testhelper.Cleanup(f.etcdClient)

	// Create supporting object
	n, err := testhelper.NewNetwork(f.context)
	h.Ok(t, err)

	// Create two subnets
	s1, err := testhelper.NewSubnet(f.context, "10.10.10.0/24", net.IPv4(10, 10, 10, 1), net.IPv4(10, 10, 10, 10), net.IPv4(10, 10, 10, 250), n)
	h.Ok(t, err)
	s2, err := testhelper.NewSubnet(f.context, "12.12.12.0/24", net.IPv4(12, 12, 12, 1), net.IPv4(12, 12, 12, 12), net.IPv4(12, 12, 12, 250), n)
	h.Ok(t, err)

	// Fetch and make sure they're present
	ss, err := f.Subnets()
	h.Ok(t, err)
	if _, ok := ss[s1.ID]; !ok {
		t.Error("Subnet #1 is missing from list")
	}
	h.Equals(t, ss[s1.ID].CIDR.String(), "10.10.10.0/24")
	if _, ok := ss[s2.ID]; !ok {
		t.Error("Subnet #2 is missing from list")
	}
	h.Equals(t, ss[s2.ID].CIDR.String(), "12.12.12.0/24")

}

示例#10
文件: connect_vde_switch.go 项目: wrouesnel/cgo.lwipv6

func main() {
	flag.Parse()

	lwipv6.Initialize(0)
	defer lwipv6.Finish()

	intf := lwipv6.CreateInterface(lwipv6.IF_VDE, *socket, 0)
	if intf == nil {
		log.Fatalln("Interface setup failed to:", *socket)
	}

	ip := net.IPv4(192, 168, 123, 2)
	mask := net.IPMask(net.IPv4(255, 255, 255, 0))
	if intf.AddAddress(net.IPNet{ip, mask}) != 0 {
		log.Fatalln("Adding address failed.")
	}

	if intf.IfUp(0) != 0 {
		log.Fatalln("Failed bringing interface up")
	}

	fmt.Println("Interface up successfully! Press any key to exit.")
	var input string
	fmt.Scanln(&input)
	fmt.Println("Exiting.")
}

示例#11
文件: roundrobin_test.go 项目: hortonworks/kubernetes-yarn

func TestStickyLoadBalanaceWorksWithMultipleEndpointsStickyNone(t *testing.T) {
	client1 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}
	client2 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 2), Port: 0}
	client3 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 3), Port: 0}
	loadBalancer := NewLoadBalancerRR()
	endpoint, err := loadBalancer.NextEndpoint("foo", nil)
	if err == nil || len(endpoint) != 0 {
		t.Errorf("Didn't fail with non-existent service")
	}

	loadBalancer.NewService("foo", api.AffinityTypeNone, 0)
	endpoints := make([]api.Endpoints, 1)
	endpoints[0] = api.Endpoints{
		ObjectMeta: api.ObjectMeta{Name: "foo"},
		Endpoints:  []string{"endpoint:1", "endpoint:2", "endpoint:3"},
	}
	loadBalancer.OnUpdate(endpoints)
	expectEndpoint(t, loadBalancer, "foo", "endpoint:1", client1)
	expectEndpoint(t, loadBalancer, "foo", "endpoint:2", client1)
	expectEndpoint(t, loadBalancer, "foo", "endpoint:3", client2)
	expectEndpoint(t, loadBalancer, "foo", "endpoint:1", client2)
	expectEndpoint(t, loadBalancer, "foo", "endpoint:2", client3)
	expectEndpoint(t, loadBalancer, "foo", "endpoint:3", client3)
	expectEndpoint(t, loadBalancer, "foo", "endpoint:1", client1)
	expectEndpoint(t, loadBalancer, "foo", "endpoint:2", client1)
}

示例#12
文件: machiner_test.go 项目: kapilt/juju

func (s *MachinerSuite) TestMachineAddresses(c *gc.C) {
	s.PatchValue(machiner.InterfaceAddrs, func() ([]net.Addr, error) {
		addrs := []net.Addr{
			&net.IPAddr{IP: net.IPv4(10, 0, 0, 1)},
			&net.IPAddr{IP: net.IPv4(127, 0, 0, 1)},
			&net.IPAddr{IP: net.IPv6loopback},
			&net.UnixAddr{}, // not IP, ignored
			&net.IPNet{IP: net.ParseIP("2001:db8::1")},
			&net.IPAddr{IP: net.IPv4(169, 254, 1, 20)}, // LinkLocal Ignored
			&net.IPNet{IP: net.ParseIP("fe80::1")},     // LinkLocal Ignored
		}
		return addrs, nil
	})
	mr := s.makeMachiner()
	defer worker.Stop(mr)
	c.Assert(s.machine.Destroy(), gc.IsNil)
	s.State.StartSync()
	c.Assert(mr.Wait(), gc.Equals, worker.ErrTerminateAgent)
	c.Assert(s.machine.Refresh(), gc.IsNil)
	c.Assert(s.machine.MachineAddresses(), jc.DeepEquals, []network.Address{
		network.NewAddress("2001:db8::1", network.ScopeUnknown),
		network.NewAddress("::1", network.ScopeMachineLocal),
		network.NewAddress("10.0.0.1", network.ScopeCloudLocal),
		network.NewAddress("127.0.0.1", network.ScopeMachineLocal),
	})
}

示例#13
文件: handler_test.go 项目: stratospark/torro

func TestInitiateHandshakes(t *testing.T) {
	Convey("Sends out handshake request to every IP in list", t, func() {
		s := NewBTService(port, []byte(peerIDRemote))
		mc := NewMockConnectionFetcher()
		s.ConnectionFetcher = mc
		s.AddHash(hash)
		_ = s.StartListening()

		// TODO: check that peer data is saved within service data structure
		peers := make([]structure.Peer, 2)
		peers[0] = structure.Peer{IP: net.IPv4(192, 168, 1, 1), Port: 55556}
		peers[1] = structure.Peer{IP: net.IPv4(192, 168, 1, 2), Port: 55557}
		s.InitiateHandshakes(hash, peers)

		for _, p := range peers {
			c0 := mc.Conns[p.AddrString()].Conn.(*MockConnection)
			hs, err := structure.ReadHandshake(bytes.NewReader(<-c0.ReceiveBytesChan))
			So(hs, ShouldNotBeNil)
			So(err, ShouldBeNil)
			hs, _ = structure.NewHandshake(hash, []byte(peerIDClient))
			c0.SendMessage(hs)
		}

		time.Sleep(time.Millisecond)
		So(len(s.Peers), ShouldEqual, len(peers))

		_ = s.StopListening()
		time.Sleep(time.Millisecond)
		So(s.Listening, ShouldBeFalse)
	})
}

示例#14
文件: benchmark_test.go 项目: ijayasin/ipaddr

func BenchmarkSummarizeIPv4(b *testing.B) {
	fip, lip := net.IPv4(172, 16, 1, 1), net.IPv4(172, 16, 255, 255)

	for i := 0; i < b.N; i++ {
		ipaddr.Summarize(fip, lip)
	}
}

示例#15
文件: icmp_test.go 项目: ChongFeng/beats

func TestIcmpIsLocalIp(t *testing.T) {
	icmp := Icmp{localIps: []net.IP{net.IPv4(192, 168, 0, 1), net.IPv4(192, 168, 0, 2)}}

	assert.True(t, icmp.isLocalIp(net.IPv4(127, 0, 0, 1)), "loopback IP")
	assert.True(t, icmp.isLocalIp(net.IPv4(192, 168, 0, 1)), "local IP")
	assert.False(t, icmp.isLocalIp(net.IPv4(10, 0, 0, 1)), "remote IP")
}

示例#16
文件: match.go 项目: yebinMoon/cherry

func (r *Match) UnmarshalBinary(data []byte) error {
	if len(data) < 40 {
		return openflow.ErrInvalidPacketLength
	}

	r.wildcards = new(Wildcard)
	if err := r.wildcards.UnmarshalBinary(data[0:4]); err != nil {
		return err
	}
	r.inPort = binary.BigEndian.Uint16(data[4:6])
	r.srcMAC = make(net.HardwareAddr, 6)
	copy(r.srcMAC, data[6:12])
	r.dstMAC = make(net.HardwareAddr, 6)
	copy(r.dstMAC, data[12:18])
	r.vlanID = binary.BigEndian.Uint16(data[18:20])
	r.vlanPriority = data[20]
	// data[21] = padding
	r.etherType = binary.BigEndian.Uint16(data[22:24])
	r.protocol = data[25]
	// data[26:28] = padding
	r.srcIP = net.IPv4(data[28], data[29], data[30], data[31])
	r.dstIP = net.IPv4(data[32], data[33], data[34], data[35])
	r.srcPort = binary.BigEndian.Uint16(data[36:38])
	r.dstPort = binary.BigEndian.Uint16(data[38:40])

	return nil
}

示例#17
文件: PacketParse.go 项目: jvortega/mimir

func (p *Packet) parseIPv4() (err error) {
	p.Protocol = p.Payload[9]
	srcIP := p.Payload[12:16]
	dstIP := p.Payload[16:20]
	p.Header.SrcIP = net.IPv4(srcIP[0], srcIP[1], srcIP[2], srcIP[3])
	p.Header.DstIP = net.IPv4(dstIP[0], dstIP[1], dstIP[2], dstIP[3])
	p.HeaderLen = uint8(p.Payload[0]) & 0x0F
	p.Length = uint16(binary.BigEndian.Uint16(p.Data[2:4]))
	pEnd := int(p.Length)
	if pEnd > len(p.Payload) {
		pEnd = len(p.Payload)
	}
	if len(p.Payload) <= int(p.HeaderLen)*4 || int(p.HeaderLen)*4 > pEnd {
		return errors.New("Packet is smaller than header.")
	}

	p.Payload = p.Payload[p.HeaderLen*4 : pEnd]
	switch p.Protocol {
	case IP_TCP:
		err = p.parseTCP()
	case IP_UDP:
		err = p.parseUDP()
	case IP_ICMP:
		err = p.parseICMP()
	default:
		fmt.Printf("Unknown IP packet type of %v\n", p.Protocol)
		err = p.parseGeneric()
	}

	return err
}

示例#18
文件: options_test.go 项目: NeilW/cni

func validateRoutes(t *testing.T, routes []plugin.Route) {
	expected := []plugin.Route{
		plugin.Route{
			Dst: net.IPNet{
				IP:   net.IPv4(10, 0, 0, 0),
				Mask: net.CIDRMask(8, 32),
			},
			GW: net.IPv4(10, 1, 2, 3),
		},
		plugin.Route{
			Dst: net.IPNet{
				IP:   net.IPv4(192, 168, 1, 0),
				Mask: net.CIDRMask(24, 32),
			},
			GW: net.IPv4(192, 168, 2, 3),
		},
	}

	if len(routes) != len(expected) {
		t.Fatalf("wrong length slice; expected %v, got %v", len(expected), len(routes))
	}

	for i := 0; i < len(routes); i++ {
		a := routes[i]
		e := expected[i]

		if a.Dst.String() != e.Dst.String() {
			t.Errorf("route.Dst mismatch: expected %v, got %v", e.Dst, a.Dst)
		}

		if !a.GW.Equal(e.GW) {
			t.Errorf("route.GW mismatch: expected %v, got %v", e.GW, a.GW)
		}
	}
}

示例#19
文件: network.go 项目: delkyd/docker

func (mapper *PortMapper) Map(port int, backendAddr net.Addr) error {
	if _, isTCP := backendAddr.(*net.TCPAddr); isTCP {
		backendPort := backendAddr.(*net.TCPAddr).Port
		backendIP := backendAddr.(*net.TCPAddr).IP
		if err := mapper.iptablesForward("-A", port, "tcp", backendIP.String(), backendPort); err != nil {
			return err
		}
		mapper.tcpMapping[port] = backendAddr.(*net.TCPAddr)
		proxy, err := NewProxy(&net.TCPAddr{IP: net.IPv4(0, 0, 0, 0), Port: port}, backendAddr)
		if err != nil {
			mapper.Unmap(port, "tcp")
			return err
		}
		mapper.tcpProxies[port] = proxy
		go proxy.Run()
	} else {
		backendPort := backendAddr.(*net.UDPAddr).Port
		backendIP := backendAddr.(*net.UDPAddr).IP
		if err := mapper.iptablesForward("-A", port, "udp", backendIP.String(), backendPort); err != nil {
			return err
		}
		mapper.udpMapping[port] = backendAddr.(*net.UDPAddr)
		proxy, err := NewProxy(&net.UDPAddr{IP: net.IPv4(0, 0, 0, 0), Port: port}, backendAddr)
		if err != nil {
			mapper.Unmap(port, "udp")
			return err
		}
		mapper.udpProxies[port] = proxy
		go proxy.Run()
	}
	return nil
}

示例#20
文件: server_test.go 项目: postfix/dhcp4server

/*
 * Example Server :D
 */
func ExampleServer() {

	//Create a Lease Pool We're going to use a memory pool
	//Remember the memory is cleared on restart so you will reissue the same IP Addresses.
	myMemoryLeasePool := memorypool.MemoryPool{}

	//Lets add a list of IPs to the pool these will be served to the clients so make sure they work for you.
	// So Create Array of IPs 192.168.1.1 to 192.168.1.30
	for i := 0; i < 30; i++ {
		err := myMemoryLeasePool.AddLease(leasepool.Lease{IP: dhcp4.IPAdd(net.IPv4(192, 168, 1, 1), i)})
		if err != nil {
			log.Fatalln("Error Adding IP to pool:" + err.Error())
		}
	}

	// We set the port numbers to over 1024 (1067 & 1068) as the automated test don't have root access
	tServer, err := dhcp4server.New(
		net.IPv4(192, 168, 1, 201),
		&myMemoryLeasePool,
		dhcp4server.SetLocalAddr(net.UDPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 1067}),
		dhcp4server.SetRemoteAddr(net.UDPAddr{IP: net.IPv4bcast, Port: 1068}),
	)
	if err != nil {
		log.Fatalln("Error Configuring Server:" + err.Error())
	}

	//Start the Server...
	err = tServer.ListenAndServe()
	if err != nil {
		log.Fatalln("Error Starting Server:" + err.Error())
	}
}

示例#21
文件: useraddr_test.go 项目: projectarkc/meek

// Test that originalClientIP reads the Meek-IP and X-Forwarded-For headers if
// present.
func TestOriginalClientXForwardedFor(t *testing.T) {
	tests := []struct {
		XForwardedFor string
		Expected      net.IP
	}{
		{"", nil},
		{"1.2.3.4", net.IPv4(1, 2, 3, 4)},
		{"1:2::3:4", net.IP{0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 4}},
		{"1.2.3.4,1:2::3:4", net.IPv4(1, 2, 3, 4)},
		{"1.2.3.4, 1:2::3:4", net.IPv4(1, 2, 3, 4)},
		{"1:2::3:4, 1.2.3.4", net.IP{0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 4}},
		// Bad syntax.
		{"xyz", nil},
		{"1.2.3.4:1234", nil},
		// Only try to parse the first element
		{"1.2.3.4, xyz", net.IPv4(1, 2, 3, 4)},
		{"1.2.3.4,,,", net.IPv4(1, 2, 3, 4)},
		{"xyz, 1.2.3.4", nil},
		// X-Forwarded-For doesn't use square brackets on IPv6.
		{"[1:2::3:4]", nil},
		{"[1:2::3:4]:1234", nil},
	}

	for _, test := range tests {
		req := &http.Request{
			Header: make(http.Header),
		}
		req.Header.Set("Meek-IP", test.XForwardedFor)
		checkExpected(t, req, test.Expected)
		req.Header.Set("X-Forwarded-For", test.XForwardedFor)
		checkExpected(t, req, test.Expected)
	}
}

示例#22
文件: server.go 项目: jayallenmn/vcap-services

func parse_sockaddr(sa syscall.Sockaddr) (ipaddr net.IP, port int) {
	switch sa := sa.(type) {
	case *syscall.SockaddrInet4:
		return net.IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3]), sa.Port
	}
	return net.IPv4(0, 0, 0, 0), 0
}

示例#23
文件: processing_test.go 项目: procore/pgnetdetective

func TestAssociatePGPackets(t *testing.T) {
	metric := &metrics.QueryMetric{
		Query: "select * from table",
		QueryNetUniqueIDs: []*metrics.QueryNetUniqueID{
			&metrics.QueryNetUniqueID{
				SrcIP: net.IPv4(111, 111, 111, 111),
				Syn:   uint32(43212),
			},
		},
	}

	combinedQueryMetrics := metrics.NewQueryMetrics()
	combinedQueryMetrics.Add(metric)

	responses := []*ResponsePacket{
		&ResponsePacket{
			DstIP: net.IPv4(111, 111, 111, 111),
			Ack:   uint32(43212),
			Size:  uint64(1000),
		},
		&ResponsePacket{
			DstIP: net.IPv4(111, 111, 111, 111),
			Ack:   uint32(43212),
			Size:  uint64(1000),
		},
	}

	AssociatePGPackets(combinedQueryMetrics, responses)

	assert.Equal(t, uint64(2), combinedQueryMetrics.List[0].TotalResponsePackets)
	assert.Equal(t, uint64(2000), combinedQueryMetrics.List[0].TotalNetworkLoad)
}

示例#24
文件: main.go 项目: Cepave/lvs-metrics

func ipvsAddService(done chan bool, service, dests int) {
	ncc := client.NewNCC(*nccSocket)
	if err := ncc.Dial(); err != nil {
		log.Fatalf("Failed to connect to NCC: %v", err)
	}
	defer ncc.Close()

	svc := &ipvs.Service{
		Address:   net.IPv4(1, 1, 1, 1),
		Protocol:  syscall.IPPROTO_TCP,
		Port:      uint16(10000 + service),
		Scheduler: "wlc",
	}
	if err := ncc.IPVSAddService(svc); err != nil {
		log.Fatalf("Failed to add IPVS service: %v", err)
	}

	for i := 0; i < dests; i++ {
		dst := &ipvs.Destination{
			Address: net.IPv4(1, 1, 1, byte(i+2)),
			Port:    uint16(10000 + service),
			Flags:   ipvs.DFForwardRoute,
			Weight:  1,
		}
		if err := ncc.IPVSAddDestination(svc, dst); err != nil {
			log.Fatalf("Failed to add IPVS destination: %v", err)
		}
	}

	done <- true
}

示例#25
文件: util_test.go 项目: rw/goser

func newPbLog(record *pb.Log) {
	record.Timestamp = proto.Int64(time.Now().UnixNano())
	record.ZoneId = proto.Uint32(123456)
	record.ZonePlan = pb.ZonePlan_FREE.Enum()

	record.Http = &pb.HTTP{
		Protocol:    pb.HTTP_HTTP11.Enum(),
		Status:      proto.Uint32(200),
		HostStatus:  proto.Uint32(503),
		UpStatus:    proto.Uint32(520),
		Method:      pb.HTTP_GET.Enum(),
		ContentType: proto.String("text/html"),
		UserAgent:   proto.String(userAgent),
		Referer:     proto.String("https://www.cloudflare.com/"),
		RequestURI:  proto.String("/cdn-cgi/trace"),
	}

	record.Origin = &pb.Origin{
		Ip:       []byte(net.IPv4(1, 2, 3, 4).To4()),
		Port:     proto.Uint32(8080),
		Hostname: proto.String("www.example.com"),
		Protocol: pb.Origin_HTTPS.Enum(),
	}

	record.Country = pb.Country_US.Enum()
	record.CacheStatus = pb.CacheStatus_HIT.Enum()
	record.ServerIp = []byte(net.IPv4(192, 168, 1, 1).To4())
	record.ServerName = proto.String("metal.cloudflare.com")
	record.RemoteIp = []byte(net.IPv4(10, 1, 2, 3).To4())
	record.BytesDlv = proto.Uint64(123456)
	record.RayId = proto.String("10c73629cce30078-LAX")
}

示例#26
文件: tuples_test.go 项目: andrewkroh/beats

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

	var tuple IPPortTuple

	// from net/ip.go
	var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}

	tuple = NewIPPortTuple(4, net.IPv4(192, 168, 0, 1), 9200, net.IPv4(192, 168, 0, 2), 9201)

	assert.Equal(v4InV6Prefix, tuple.raw[0:12], "prefix_src")
	assert.Equal([]byte{192, 168, 0, 1}, tuple.raw[12:16], "src_ip")
	assert.Equal([]byte{0x23, 0xf0}, tuple.raw[16:18], "src_port")

	assert.Equal(v4InV6Prefix, tuple.raw[18:30], "prefix_dst")
	assert.Equal([]byte{192, 168, 0, 2}, tuple.raw[30:34], "dst_ip")
	assert.Equal([]byte{0x23, 0xf1}, tuple.raw[34:36], "dst_port")
	assert.Equal(36, len(tuple.raw))

	assert.Equal(v4InV6Prefix, tuple.revRaw[0:12], "rev prefix_dst")
	assert.Equal([]byte{192, 168, 0, 2}, tuple.revRaw[12:16], "rev dst_ip")
	assert.Equal([]byte{0x23, 0xf1}, tuple.revRaw[16:18], "rev dst_port")

	assert.Equal(v4InV6Prefix, tuple.revRaw[18:30], "rev prefix_src")
	assert.Equal([]byte{192, 168, 0, 1}, tuple.revRaw[30:34], "rev src_ip")
	assert.Equal([]byte{0x23, 0xf0}, tuple.revRaw[34:36], "rev src_port")
	assert.Equal(36, len(tuple.revRaw))

	tcpTuple := TCPTupleFromIPPort(&tuple, 1)
	assert.Equal(tuple.raw[:], tcpTuple.raw[0:36], "Wrong TCP tuple hashable")
	assert.Equal([]byte{0, 0, 0, 1}, tcpTuple.raw[36:40], "stream_id")
}

示例#27
文件: util_test.go 项目: rw/goser

func newCapnpLog(record *capnp.Log) {
	record.SetTimestamp(time.Now().UnixNano())
	record.SetZoneId(123456)
	record.SetZonePlan(capnp.ZONEPLAN_FREE)

	http := capnp.NewHTTP(record.Segment)
	record.SetHttp(http)
	http.SetProtocol(capnp.HTTPPROTOCOL_HTTP11)
	http.SetStatus(200)
	http.SetHostStatus(503)
	http.SetUpStatus(520)
	http.SetMethod(capnp.HTTPMETHOD_GET)
	http.SetContentType("text/html")
	http.SetUserAgent(userAgent)
	http.SetReferer("http://www.w3.org/hypertext/DataSources/Overview.html")
	http.SetRequestURI("/a9pPJR1.jpg")

	origin := capnp.NewOrigin(record.Segment)
	record.SetOrigin(origin)
	origin.SetIp([]byte(net.IPv4(1, 2, 3, 4).To4()))
	origin.SetPort(8080)
	origin.SetHostname("www.cloudflare.com")
	origin.SetProtocol(capnp.ORIGINPROTOCOL_HTTPS)

	record.SetCacheStatus(capnp.CACHESTATUS_HIT)
	record.SetServerIp([]byte(net.IPv4(192, 168, 1, 1).To4()))
	record.SetServerName("metal.cloudflare.com")
	record.SetRemoteIp([]byte(net.IPv4(10, 1, 2, 3).To4()))
	record.SetBytesDlv(123456)
	record.SetRayId("10c73629cce30078-LAX")
}

示例#28
文件: fastping_test.go 项目: kanocz/go-fastping

func TestAddIP(t *testing.T) {
	addIPTests := []struct {
		host   string
		addr   *net.IPAddr
		expect bool
	}{
		{host: "127.0.0.1", addr: &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}, expect: true},
		{host: "localhost", addr: &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}, expect: false},
	}

	p := NewPinger()

	for _, tt := range addIPTests {
		if ok := p.AddIP(tt.host); ok != nil {
			if tt.expect != false {
				t.Errorf("AddIP failed: got %v, expected %v", ok, tt.expect)
			}
		}
	}
	for _, tt := range addIPTests {
		if tt.expect {
			if !p.addrs[tt.host].IP.Equal(tt.addr.IP) {
				t.Errorf("AddIP didn't save IPAddr: %v", tt.host)
			}
		}
	}
}

示例#29
文件: roundrobin_test.go 项目: CodeJuan/kubernetes

func TestStickyLoadBalanceWorksWithMultipleEndpointsAndUpdates(t *testing.T) {
	client1 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}
	client2 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 2), Port: 0}
	client3 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 3), Port: 0}
	loadBalancer := NewLoadBalancerRR()
	service := proxy.ServicePortName{NamespacedName: types.NamespacedName{Namespace: "testnamespace", Name: "foo"}, Port: ""}
	endpoint, err := loadBalancer.NextEndpoint(service, nil, false)
	if err == nil || len(endpoint) != 0 {
		t.Errorf("Didn't fail with non-existent service")
	}

	loadBalancer.NewService(service, api.ServiceAffinityClientIP, 0)
	endpoints := make([]api.Endpoints, 1)
	endpoints[0] = api.Endpoints{
		ObjectMeta: api.ObjectMeta{Name: service.Name, Namespace: service.Namespace},
		Subsets: []api.EndpointSubset{
			{
				Addresses: []api.EndpointAddress{{IP: "endpoint"}},
				Ports:     []api.EndpointPort{{Port: 1}, {Port: 2}, {Port: 3}},
			},
		},
	}
	loadBalancer.OnEndpointsUpdate(endpoints)
	shuffledEndpoints := loadBalancer.services[service].endpoints
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client2)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client2)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[2], client3)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client2)
	// Then update the configuration with one fewer endpoints, make sure
	// we start in the beginning again
	endpoints[0] = api.Endpoints{
		ObjectMeta: api.ObjectMeta{Name: service.Name, Namespace: service.Namespace},
		Subsets: []api.EndpointSubset{
			{
				Addresses: []api.EndpointAddress{{IP: "endpoint"}},
				Ports:     []api.EndpointPort{{Port: 4}, {Port: 5}},
			},
		},
	}
	loadBalancer.OnEndpointsUpdate(endpoints)
	shuffledEndpoints = loadBalancer.services[service].endpoints
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client2)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client2)
	expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client2)

	// Clear endpoints
	endpoints[0] = api.Endpoints{ObjectMeta: api.ObjectMeta{Name: service.Name, Namespace: service.Namespace}, Subsets: nil}
	loadBalancer.OnEndpointsUpdate(endpoints)

	endpoint, err = loadBalancer.NextEndpoint(service, nil, false)
	if err == nil || len(endpoint) != 0 {
		t.Errorf("Didn't fail with non-existent service")
	}
}

示例#30
文件: policies_test.go 项目: gocql/gocql

func TestCOWList_Add(t *testing.T) {
	var cow cowHostList

	toAdd := [...]net.IP{net.IPv4(0, 0, 0, 0), net.IPv4(1, 0, 0, 0), net.IPv4(2, 0, 0, 0)}

	for _, addr := range toAdd {
		if !cow.add(&HostInfo{peer: addr}) {
			t.Fatal("did not add peer which was not in the set")
		}
	}

	hosts := cow.get()
	if len(hosts) != len(toAdd) {
		t.Fatalf("expected to have %d hosts got %d", len(toAdd), len(hosts))
	}

	set := make(map[string]bool)
	for _, host := range hosts {
		set[string(host.Peer())] = true
	}

	for _, addr := range toAdd {
		if !set[string(addr)] {
			t.Errorf("addr was not in the host list: %q", addr)
		}
	}
}

展开阅读全文