当前位置: 首页>>代码示例>>Golang>>正文


Golang net.ParseIP函数代码示例

本文整理汇总了Golang中net.ParseIP函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseIP函数的具体用法?Golang ParseIP怎么用?Golang ParseIP使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ParseIP函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestUDPProxyUpdateDelete

func TestUDPProxyUpdateDelete(t *testing.T) {
	lb := NewLoadBalancerRR()
	service := ServicePortName{types.NamespacedName{"testnamespace", "echo"}, "p"}
	lb.OnUpdate([]api.Endpoints{
		{
			ObjectMeta: api.ObjectMeta{Namespace: service.Namespace, Name: service.Name},
			Subsets: []api.EndpointSubset{{
				Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}},
				Ports:     []api.EndpointPort{{Name: "p", Port: udpServerPort}},
			}},
		},
	})

	p := CreateProxier(lb, net.ParseIP("0.0.0.0"), &fakeIptables{}, net.ParseIP("127.0.0.1"))
	waitForNumProxyLoops(t, p, 0)

	svcInfo, err := p.addServiceOnPort(service, "UDP", 0, time.Second)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	conn, err := net.Dial("udp", joinHostPort("", svcInfo.proxyPort))
	if err != nil {
		t.Fatalf("error connecting to proxy: %v", err)
	}
	conn.Close()
	waitForNumProxyLoops(t, p, 1)

	p.OnUpdate([]api.Service{})
	if err := waitForClosedPortUDP(p, svcInfo.proxyPort); err != nil {
		t.Fatalf(err.Error())
	}
	waitForNumProxyLoops(t, p, 0)
}
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:33,代码来源:proxier_test.go

示例2: TestLinuxConnections

func TestLinuxConnections(t *testing.T) {
	fs_hook.Mock(mockFS)
	defer fs_hook.Restore()
	scanner := NewConnectionScanner(process.NewWalker("/proc"))
	defer scanner.Stop()

	// let the background scanner finish its first pass
	time.Sleep(1 * time.Second)

	iter, err := scanner.Connections(true)
	if err != nil {
		t.Fatal(err)
	}
	have := iter.Next()
	want := &Connection{
		LocalAddress:  net.ParseIP("0.0.0.0").To4(),
		LocalPort:     42688,
		RemoteAddress: net.ParseIP("0.0.0.0").To4(),
		RemotePort:    0,
		inode:         5107,
		Proc: Proc{
			PID:  1,
			Name: "foo",
		},
	}
	if !reflect.DeepEqual(want, have) {
		t.Fatal(test.Diff(want, have))
	}

	if have := iter.Next(); have != nil {
		t.Fatal(have)
	}

}
开发者ID:CNDonny,项目名称:scope,代码行数:34,代码来源:spy_linux_internal_test.go

示例3: newDomain

// Function to mock a domain object
func newDomain() model.Domain {
	var domain model.Domain
	domain.FQDN = "rafael.net.br"

	domain.Nameservers = []model.Nameserver{
		{
			Host: "ns1.rafael.net.br",
			IPv4: net.ParseIP("127.0.0.1"),
			IPv6: net.ParseIP("::1"),
		},
		{
			Host: "ns2.rafael.net.br",
			IPv4: net.ParseIP("127.0.0.2"),
		},
	}

	domain.DSSet = []model.DS{
		{
			Keytag:    1234,
			Algorithm: model.DSAlgorithmRSASHA1,
			Digest:    "A790A11EA430A85DA77245F091891F73AA740483",
		},
	}

	owner, _ := mail.ParseAddress("[email protected]")
	domain.Owners = []model.Owner{
		{
			Email:    owner,
			Language: "pt-BR",
		},
	}

	return domain
}
开发者ID:rafaeljusto,项目名称:shelter,代码行数:35,代码来源:dao_domain.go

示例4: Test_getMyIP_UseIPv4False_IPProviderHasIPv6Addresses_IPv46AddressesAreReturned

// getMyIP should return the IPv6 addresses of the IP provider if the useIPv4 flag is set to false.
func Test_getMyIP_UseIPv4False_IPProviderHasIPv6Addresses_IPv46AddressesAreReturned(t *testing.T) {
	// arrange
	ipProvider := testIPProvider{
		ipv4IPs: []net.IP{
			net.ParseIP("127.0.0.1"),
		},
		ipv4Err: nil,
		ipv6IPs: []net.IP{
			net.ParseIP("::1"),
		},
		ipv6Err: nil,
	}
	selectionOption := "all"
	useIPv4 := false

	// act
	ips, _ := getMyIP(ipProvider, selectionOption, useIPv4)

	// assert
	expectedResult := []net.IP{
		net.ParseIP("::1"),
	}
	if fmt.Sprintf("%s", ips) != fmt.Sprintf("%s", expectedResult) {
		t.Fail()
		t.Logf("getMyIP(ipProvider, %q, %v) returned %q but should have returned %q", selectionOption, useIPv4, ips, expectedResult)
	}

}
开发者ID:andreaskoch,项目名称:myip-cli,代码行数:29,代码来源:myip_test.go

示例5: NewKubeletServer

// NewKubeletServer will create a new KubeletServer with default values.
func NewKubeletServer() *KubeletServer {
	return &KubeletServer{
		Address:                     net.ParseIP("0.0.0.0"),
		AuthPath:                    util.NewStringFlag("/var/lib/kubelet/kubernetes_auth"), // deprecated
		CAdvisorPort:                4194,
		CertDirectory:               "/var/run/kubernetes",
		CgroupRoot:                  "",
		ConfigureCBR0:               false,
		ContainerRuntime:            "docker",
		CPUCFSQuota:                 false,
		DockerDaemonContainer:       "/docker-daemon",
		DockerExecHandlerName:       "native",
		EventBurst:                  10,
		EventRecordQPS:              5.0,
		EnableDebuggingHandlers:     true,
		EnableServer:                true,
		FileCheckFrequency:          20 * time.Second,
		HealthzBindAddress:          net.ParseIP("127.0.0.1"),
		HealthzPort:                 10248,
		HostNetworkSources:          kubetypes.AllSource,
		HostPIDSources:              kubetypes.AllSource,
		HostIPCSources:              kubetypes.AllSource,
		HTTPCheckFrequency:          20 * time.Second,
		ImageGCHighThresholdPercent: 90,
		ImageGCLowThresholdPercent:  80,
		KubeConfig:                  util.NewStringFlag("/var/lib/kubelet/kubeconfig"),
		LowDiskSpaceThresholdMB:     256,
		MasterServiceNamespace:      api.NamespaceDefault,
		MaxContainerCount:           100,
		MaxPerPodContainerCount:     2,
		MaxOpenFiles:                1000000,
		MaxPods:                     40,
		MinimumGCAge:                1 * time.Minute,
		NetworkPluginDir:            "/usr/libexec/kubernetes/kubelet-plugins/net/exec/",
		NetworkPluginName:           "",
		NodeLabels:                  []string{},
		NodeLabelsFile:              "",
		NodeStatusUpdateFrequency:   10 * time.Second,
		OOMScoreAdj:                 qos.KubeletOOMScoreAdj,
		PodInfraContainerImage:      dockertools.PodInfraContainerImage,
		Port:                           ports.KubeletPort,
		ReadOnlyPort:                   ports.KubeletReadOnlyPort,
		RegisterNode:                   true, // will be ignored if no apiserver is configured
		RegisterSchedulable:            true,
		RegistryBurst:                  10,
		RegistryPullQPS:                5.0,
		ResourceContainer:              "/kubelet",
		RktPath:                        "",
		RktStage1Image:                 "",
		RootDirectory:                  defaultRootDir,
		SerializeImagePulls:            true,
		StreamingConnectionIdleTimeout: 5 * time.Minute,
		SyncFrequency:                  1 * time.Minute,
		SystemContainer:                "",
		ReconcileCIDR:                  true,
		KubeAPIQPS:                     5.0,
		KubeAPIBurst:                   10,
		ExperimentalFlannelOverlay:     experimentalFlannelOverlay,
	}
}
开发者ID:robertabbott,项目名称:kubernetes,代码行数:61,代码来源:server.go

示例6: openPortal

func (proxier *Proxier) openPortal(service proxy.ServicePortName, info *serviceInfo) error {
	err := proxier.openOnePortal(info.portal, info.protocol, proxier.listenIP, info.proxyPort, service)
	if err != nil {
		return err
	}
	for _, publicIP := range info.externalIPs {
		err = proxier.openOnePortal(portal{net.ParseIP(publicIP), info.portal.port, true}, info.protocol, proxier.listenIP, info.proxyPort, service)
		if err != nil {
			return err
		}
	}
	for _, ingress := range info.loadBalancerStatus.Ingress {
		if ingress.IP != "" {
			err = proxier.openOnePortal(portal{net.ParseIP(ingress.IP), info.portal.port, false}, info.protocol, proxier.listenIP, info.proxyPort, service)
			if err != nil {
				return err
			}
		}
	}
	if info.nodePort != 0 {
		err = proxier.openNodePort(info.nodePort, info.protocol, proxier.listenIP, info.proxyPort, service)
		if err != nil {
			return err
		}
	}
	return nil
}
开发者ID:numidiasoft,项目名称:kubernetes,代码行数:27,代码来源:proxier.go

示例7: Test_getMyIP_UseIPv4True_IPProviderReturnsError_NoIPsAreReturned_ErrorIsReturned

// getMyIP (useIPv4 = true) should only return an error if the IP provider returns an error.
func Test_getMyIP_UseIPv4True_IPProviderReturnsError_NoIPsAreReturned_ErrorIsReturned(t *testing.T) {
	// arrange
	ipProvider := testIPProvider{
		ipv4IPs: []net.IP{
			net.ParseIP("127.0.0.1"),
		},
		ipv4Err: fmt.Errorf("IPv4 error"),
		ipv6IPs: []net.IP{
			net.ParseIP("::1"),
		},
		ipv6Err: fmt.Errorf("IPv6 error"),
	}
	selectionOption := "all"
	useIPv4 := false

	// act
	ips, err := getMyIP(ipProvider, selectionOption, useIPv4)

	// assert
	if len(ips) > 0 {
		t.Fail()
		t.Logf("getMyIP(ipProvider, %q, %v) returned %q but should not have returned anything because the IP provider returned an error", selectionOption, useIPv4, ips)
	}

	if err == nil {
		t.Fail()
		t.Logf("getMyIP(ipProvider, %q, %v) did not return an error even though the IP Provider responded with one.", selectionOption, useIPv4)
	}

}
开发者ID:andreaskoch,项目名称:myip-cli,代码行数:31,代码来源:myip_test.go

示例8: resolveHost

// Resolve a hostname to an IP address using the system DNS settings first, then HypeDNS
func resolveHost(hostname string) (ips []string, err error) {
	var ip string
	// Try the system DNS setup
	result, _ := net.LookupHost(hostname)
	if len(result) > 0 {
		goto end
	}

	// Try with hypedns
	ip, err = lookupHypeDNS(hostname)

	if ip == "" || err != nil {
		err = fmt.Errorf("Unable to resolve hostname. This is usually caused by not having a route to hypedns. Please try again in a few seconds.")
		return
	}

	result = append(result, ip)

end:
	for _, addr := range result {
		tIP := net.ParseIP(addr)
		// Only grab the cjdns IP's
		if tIP[0] == 0xfc {
			ips = append(ips, padIPv6(net.ParseIP(addr)))
		}
	}

	return
}
开发者ID:ryansb,项目名称:cjdcmd,代码行数:30,代码来源:dns.go

示例9: TestStore

func TestStore(t *testing.T) {
	fakeClient, storage, backing := newStorage(t)
	if _, err := fakeClient.Set(key(), runtime.EncodeOrDie(testapi.Default.Codec(), validNewRangeAllocation()), 0); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	if err := storage.Allocate(net.ParseIP("192.168.1.2")); err != nil {
		t.Fatal(err)
	}
	ok, err := backing.Allocate(1)
	if err != nil {
		t.Fatal(err)
	}
	if ok {
		t.Fatal("Expected allocation to fail")
	}
	if err := storage.Allocate(net.ParseIP("192.168.1.2")); err != ipallocator.ErrAllocated {
		t.Fatal(err)
	}

	obj := fakeClient.Data[key()]
	if obj.R == nil || obj.R.Node == nil {
		t.Fatalf("%s is empty: %#v", key(), obj)
	}
	t.Logf("data: %#v", obj.R.Node)
}
开发者ID:johnmccawley,项目名称:origin,代码行数:26,代码来源:etcd_test.go

示例10: UnmarshalJSON

func (ncfg *networkConfiguration) UnmarshalJSON(b []byte) error {
	var (
		err  error
		nMap map[string]interface{}
	)

	if err = json.Unmarshal(b, &nMap); err != nil {
		return err
	}

	if v, ok := nMap["AddressIPv4"]; ok {
		if ncfg.AddressIPv4, err = types.ParseCIDR(v.(string)); err != nil {
			return types.InternalErrorf("failed to decode bridge network address IPv4 after json unmarshal: %s", v.(string))
		}
	}

	if v, ok := nMap["AddressIPv6"]; ok {
		if ncfg.AddressIPv6, err = types.ParseCIDR(v.(string)); err != nil {
			return types.InternalErrorf("failed to decode bridge network address IPv6 after json unmarshal: %s", v.(string))
		}
	}

	ncfg.DefaultBindingIP = net.ParseIP(nMap["DefaultBindingIP"].(string))
	ncfg.DefaultGatewayIPv4 = net.ParseIP(nMap["DefaultGatewayIPv4"].(string))
	ncfg.DefaultGatewayIPv6 = net.ParseIP(nMap["DefaultGatewayIPv6"].(string))
	ncfg.ID = nMap["ID"].(string)
	ncfg.BridgeName = nMap["BridgeName"].(string)
	ncfg.EnableIPv6 = nMap["EnableIPv6"].(bool)
	ncfg.EnableIPMasquerade = nMap["EnableIPMasquerade"].(bool)
	ncfg.EnableICC = nMap["EnableICC"].(bool)
	ncfg.Mtu = int(nMap["Mtu"].(float64))

	return nil
}
开发者ID:thieman,项目名称:libnetwork,代码行数:34,代码来源:bridge_store.go

示例11: applyNetConf

func applyNetConf(link netlink.Link, netConf config.InterfaceConfig) error {
	if netConf.DHCP {
		log.Infof("Running DHCP on %s", link.Attrs().Name)
		cmd := exec.Command("dhcpcd", "-A4", "-e", "force_hostname=true", link.Attrs().Name)
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		if err := cmd.Run(); err != nil {
			log.Error(err)
		}
	} else if netConf.IPV4LL {
		if err := AssignLinkLocalIP(link); err != nil {
			log.Error("IPV4LL set failed")
			return err
		}
	} else if netConf.Address == "" {
		return nil
	} else {
		addr, err := netlink.ParseAddr(netConf.Address)
		if err != nil {
			return err
		}
		if err := netlink.AddrAdd(link, addr); err != nil {
			log.Error("addr add failed")
			return err
		}
		log.Infof("Set %s on %s", netConf.Address, link.Attrs().Name)
	}

	if netConf.MTU > 0 {
		if err := netlink.LinkSetMTU(link, netConf.MTU); err != nil {
			log.Error("set MTU Failed")
			return err
		}
	}

	if err := netlink.LinkSetUp(link); err != nil {
		log.Error("failed to setup link")
		return err
	}

	if netConf.Gateway != "" {
		gatewayIp := net.ParseIP(netConf.Gateway)
		if gatewayIp == nil {
			return errors.New("Invalid gateway address " + netConf.Gateway)
		}

		route := netlink.Route{
			Scope: netlink.SCOPE_UNIVERSE,
			Gw:    net.ParseIP(netConf.Gateway),
		}
		if err := netlink.RouteAdd(&route); err != nil {
			log.Error("gateway set failed")
			return err
		}

		log.Infof("Set default gateway %s", netConf.Gateway)
	}

	return nil
}
开发者ID:jgatkinsn,项目名称:os,代码行数:60,代码来源:network.go

示例12: TestPrune

// Check that we can prune an answer
func TestPrune(t *testing.T) {
	InitDefaultLogging(testing.Verbose())
	Info.Println("TestPrune starting")

	questionMsg := new(dns.Msg)
	questionMsg.SetQuestion("name", dns.TypeA)
	questionMsg.RecursionDesired = true
	question := &questionMsg.Question[0]
	records := []ZoneRecord{
		Record{"name", net.ParseIP("10.0.1.1"), 0, 0, 0},
		Record{"name", net.ParseIP("10.0.1.2"), 0, 0, 0},
		Record{"name", net.ParseIP("10.0.1.3"), 0, 0, 0},
		Record{"name", net.ParseIP("10.0.1.4"), 0, 0, 0},
	}

	reply := makeAddressReply(questionMsg, question, records, DefaultLocalTTL)
	reply.Answer[0].Header().Ttl = DefaultLocalTTL

	pruned := pruneAnswers(reply.Answer, 1)
	require.Equal(t, 1, len(pruned), "wrong number of answers")

	pruned = pruneAnswers(reply.Answer, 2)
	require.Equal(t, 2, len(pruned), "wrong number of answers")

	pruned = pruneAnswers(reply.Answer, 0)
	require.Equal(t, len(records), len(pruned), "wrong number of answers")
}
开发者ID:rahulxkrishna,项目名称:weave,代码行数:28,代码来源:dns_test.go

示例13: TestClusterConfig_translateAddressAndPort_Success

func TestClusterConfig_translateAddressAndPort_Success(t *testing.T) {
	cfg := NewCluster()
	cfg.AddressTranslator = staticAddressTranslator(net.ParseIP("10.10.10.10"), 5432)
	newAddr, newPort := cfg.translateAddressPort(net.ParseIP("10.0.0.1"), 2345)
	assertTrue(t, "translated address", net.ParseIP("10.10.10.10").Equal(newAddr))
	assertEqual(t, "translated port", 5432, newPort)
}
开发者ID:gocql,项目名称:gocql,代码行数:7,代码来源:cluster_test.go

示例14: TestClusterConfig_translateAddressAndPort_NilTranslator

func TestClusterConfig_translateAddressAndPort_NilTranslator(t *testing.T) {
	cfg := NewCluster()
	assertNil(t, "cluster config address translator", cfg.AddressTranslator)
	newAddr, newPort := cfg.translateAddressPort(net.ParseIP("10.0.0.1"), 1234)
	assertTrue(t, "same address as provided", net.ParseIP("10.0.0.1").Equal(newAddr))
	assertEqual(t, "translated host and port", 1234, newPort)
}
开发者ID:gocql,项目名称:gocql,代码行数:7,代码来源:cluster_test.go

示例15: TestUDPProxyTimeout

func TestUDPProxyTimeout(t *testing.T) {
	lb := NewLoadBalancerRR()
	service := proxy.ServicePortName{NamespacedName: types.NamespacedName{Namespace: "testnamespace", Name: "echo"}, Port: "p"}
	lb.OnEndpointsUpdate([]api.Endpoints{
		{
			ObjectMeta: api.ObjectMeta{Name: service.Name, Namespace: service.Namespace},
			Subsets: []api.EndpointSubset{{
				Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}},
				Ports:     []api.EndpointPort{{Name: "p", Port: udpServerPort}},
			}},
		},
	})

	p, err := createProxier(lb, net.ParseIP("0.0.0.0"), ipttest.NewFake(), net.ParseIP("127.0.0.1"), nil, time.Minute, time.Second, udpIdleTimeoutForTest)
	if err != nil {
		t.Fatal(err)
	}
	waitForNumProxyLoops(t, p, 0)

	svcInfo, err := p.addServiceOnPort(service, "UDP", 0, time.Second)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	waitForNumProxyLoops(t, p, 1)
	testEchoUDP(t, "127.0.0.1", svcInfo.proxyPort)
	// When connecting to a UDP service endpoint, there should be a Conn for proxy.
	waitForNumProxyClients(t, svcInfo, 1, time.Second)
	// If conn has no activity for serviceInfo.timeout since last Read/Write, it should be closed because of timeout.
	waitForNumProxyClients(t, svcInfo, 0, 2*time.Second)
}
开发者ID:Q-Lee,项目名称:kubernetes,代码行数:30,代码来源:proxier_test.go


注:本文中的net.ParseIP函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。