當前位置: 首頁>>代碼示例>>Golang>>正文


Golang net.ResolveIPAddr函數代碼示例

本文整理匯總了Golang中net.ResolveIPAddr函數的典型用法代碼示例。如果您正苦於以下問題:Golang ResolveIPAddr函數的具體用法?Golang ResolveIPAddr怎麽用?Golang ResolveIPAddr使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了ResolveIPAddr函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: matchSubnet

func matchSubnet(patterns []string, addresses ...string) (bool, bool, error) {
	oneValidPattern := false
	for _, p := range patterns {
		for _, a := range addresses {
			ip, err := net.ResolveIPAddr("ip", a)
			if err != nil {
				errors.Trace(errors.Annotate(err, "could not parse machine's address"))
				continue
			} else if pip, err := net.ResolveIPAddr("ip", p); err == nil {
				oneValidPattern = true
				if ip.IP.Equal(pip.IP) {
					return true, true, nil
				}
			} else if pip := net.ParseIP(p); pip != nil {
				oneValidPattern = true
				if ip.IP.Equal(pip) {
					return true, true, nil
				}
			} else if _, ipNet, err := net.ParseCIDR(p); err == nil {
				oneValidPattern = true
				if ipNet.Contains(ip.IP) {
					return true, true, nil
				}
			}
		}
	}
	return false, oneValidPattern, nil
}
開發者ID:imoapps,項目名稱:juju,代碼行數:28,代碼來源:filtering.go

示例2: ApiStruct2Peer

func ApiStruct2Peer(p *gobgpapi.Peer) *Peer {
	localCaps := capabilities{}
	remoteCaps := capabilities{}
	for _, buf := range p.Conf.LocalCap {
		c, _ := bgp.DecodeCapability(buf)
		localCaps = append(localCaps, c)
	}
	for _, buf := range p.Conf.RemoteCap {
		c, _ := bgp.DecodeCapability(buf)
		remoteCaps = append(remoteCaps, c)
	}
	remoteIp, _ := net.ResolveIPAddr("ip", p.Conf.NeighborAddress)
	localIp, _ := net.ResolveIPAddr("ip", p.Conf.LocalAddress)
	conf := PeerConf{
		RemoteIp:     remoteIp.String(),
		Id:           net.ParseIP(p.Conf.Id),
		RemoteAs:     p.Conf.PeerAs,
		LocalAs:      p.Conf.LocalAs,
		RemoteCap:    remoteCaps,
		LocalCap:     localCaps,
		PrefixLimits: p.Conf.PrefixLimits,
		LocalIp:      localIp.String(),
		Interface:    p.Conf.NeighborInterface,
	}
	return &Peer{
		Conf:           conf,
		Info:           p.Info,
		Timers:         p.Timers,
		RouteReflector: p.RouteReflector,
		RouteServer:    p.RouteServer,
	}
}
開發者ID:luizbafilho,項目名稱:fusis,代碼行數:32,代碼來源:common.go

示例3: initSessions

func initSessions() {
	recvAddr, _ := net.ResolveIPAddr("ip", "127.0.0.1")
	senderAddr, _ = net.ResolveIPAddr("ip", "127.0.0.2")

	// Create a UDP transport with "local" address and use this for a "local" RTP session
	// Not used in these tests, used to initialize and get a Session
	tpRecv, _ := NewTransportUDP(recvAddr, recvPort, localZone)

	// TransportUDP implements RtpTransportWrite and RtpTransportRecv interfaces thus
	// set it in the RtpSession for both interfaces
	rsRecv = NewSession(tpRecv, tpRecv)

	// Create and store the data receive channel.
	dataReceiver = rsRecv.CreateDataReceiveChan()

	// Create a media stream.
	// The SSRC identifies the stream. Each stream has its own sequence number and other
	// context. A RTP session can have several RTP stream for example to send several
	// streams of the same media. Need an output stream to test for collisions/loops
	//
	strIdx, _ := rsRecv.NewSsrcStreamOut(&Address{recvAddr.IP, recvPort, recvPort + 1, localZone}, 0x01020304, 0x4711)
	rsRecv.SsrcStreamOutForIndex(strIdx).SetSdesItem(SdesCname, "AAAAAA")
	rsRecv.SsrcStreamOutForIndex(strIdx).SetPayloadType(0)
	rsRecv.rtcpServiceActive = true // to simulate an active RTCP service

	tpSender, _ := NewTransportUDP(senderAddr, senderPort, remoteZone)
	rsSender = NewSession(tpSender, tpSender)
}
開發者ID:evelyn2000,項目名稱:GoRTP,代碼行數:28,代碼來源:receive_test.go

示例4: TestSet

func TestSet(t *testing.T) {
	t.Parallel()
	hCopy := sample(t)
	one0, err := net.ResolveIPAddr("ip", "10.0.0.1")
	ok(t, err)
	hCopy.Set(*one0, "tendot")
	equals(t, len(hCopy.records), 4)
	equals(t, hCopy.records[3].Hostnames["tendot"], true)
	equals(t, hCopy.records[3].IpAddress.String(), "10.0.0.1")

	// appending same element shouldn't change anything
	hCopy.Set(*one0, "tendot")
	equals(t, len(hCopy.records), 4)

	one92, err := net.ResolveIPAddr("ip", "192.168.3.7")
	ok(t, err)
	hCopy.Set(*one92, "tendot")
	equals(t, hCopy.records[3].IpAddress.String(), "192.168.3.7")

	ip6, err := net.ResolveIPAddr("ip", "::1")
	ok(t, err)
	hCopy.Set(*ip6, "tendot")
	equals(t, len(hCopy.records), 5)
	equals(t, hCopy.records[4].IpAddress.String(), "::1")
}
開發者ID:kevinburke,項目名稱:hostsfile,代碼行數:25,代碼來源:hostsfile_test.go

示例5: Ping

func Ping(hostName string, id uint16, sequence uint16, payload []byte) os.Error {

	localAddr, e := net.ResolveIPAddr("0.0.0.0")
	if e != nil {
		fmt.Printf("%s\n", e)
		return e
	}

	remoteAddr, e := net.ResolveIPAddr(hostName)
	if e != nil {
		fmt.Printf("%s\n", e)
		return e
	}

	cl, e := NewPingClient(localAddr)
	if e != nil {
		fmt.Printf("%s\n", e)
		return e
	}

	cl.SendEchoRequest(remoteAddr, id, sequence, payload)
	cl.Close()

	return nil
}
開發者ID:PerArneng,項目名稱:goping,代碼行數:25,代碼來源:ping.go

示例6: filterAddr

func (s *store) filterAddr(addrs []string, filter string) ([]string, error) {
	host, port, err := net.SplitHostPort(filter)
	if err != nil {
		return nil, err
	}

	ip, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		return nil, err
	}

	var joinPeers []string
	for _, addr := range addrs {
		joinHost, joinPort, err := net.SplitHostPort(addr)
		if err != nil {
			return nil, err
		}

		joinIp, err := net.ResolveIPAddr("ip", joinHost)
		if err != nil {
			return nil, err
		}

		// Don't allow joining ourselves
		if ip.String() == joinIp.String() && port == joinPort {
			continue
		}
		joinPeers = append(joinPeers, addr)
	}
	return joinPeers, nil
}
開發者ID:hawson,項目名稱:influxdb,代碼行數:31,代碼來源:store.go

示例7: TestProtocols

func TestProtocols(t *testing.T) {
	t.Parallel()
	one92, _ := net.ResolveIPAddr("ip", "192.168.3.7")
	ip6, _ := net.ResolveIPAddr("ip", "::1")
	equals(t, matchProtocols(one92.IP, ip6.IP), false)
	equals(t, matchProtocols(one92.IP, one92.IP), true)
	equals(t, matchProtocols(ip6.IP, ip6.IP), true)
}
開發者ID:kevinburke,項目名稱:hostsfile,代碼行數:8,代碼來源:hostsfile_test.go

示例8: main

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	bcastIP := "127.0.0.1"
	flag.Parse()
	if myID == -1 || nGroup == -1 {
		log.Panic("usage")
	}
	log.Printf("upaxos id(%d) started in group of %d", myID, nGroup)
	defer log.Printf("upaxos id(%d) ending", myID)

	lfr, lfw := logfile(myID)
	promises, accepts, learnings := loadLogData(lfr)
	lfw.Printf("starting %d", myID)

	// begin listening on my well known address
	la, err := net.ResolveIPAddr("ip4", bcastIP)
	if err != nil {
		log.Panic(err)
	}
	conn, err := net.ListenIP(groupIPProto, la)
	if err != nil {
		log.Panic(err)
	}

	sendDest, err = net.ResolveIPAddr("ip4", bcastIP)
	if err != nil {
		log.Panic(err)
	}

	leadc := make(chan Msg)
	acceptc := make(chan Msg)
	learnc := make(chan Msg)
	mainc := make(chan Msg)
	receivers = []chan Msg{leadc, acceptc, learnc, mainc}
	go lead(leadc)
	go accept(acceptc, lfw, promises, accepts)
	go learn(learnc, lfw, learnings)
	go listen(conn)
loop:
	for m := range mainc {
		if len(m.f) > 0 {
			switch m.f[0] {
			case "quit":
				fallthrough
			case "exit":
				fallthrough
			case "bye":
				log.Print("exiting")
				break loop
			}
		}
	}
}
開發者ID:ecashin,項目名稱:go-getting,代碼行數:53,代碼來源:upaxos.go

示例9: dialTCP

func dialTCP(target string, w http.ResponseWriter, module Module) (net.Conn, error) {
	var dialProtocol, fallbackProtocol string

	dialer := &net.Dialer{Timeout: module.Timeout}
	if module.TCP.Protocol == "" {
		module.TCP.Protocol = "tcp"
	}
	if module.TCP.Protocol == "tcp" && module.TCP.PreferredIpProtocol == "" {
		module.TCP.PreferredIpProtocol = "ip6"
	}
	if module.TCP.PreferredIpProtocol == "ip6" {
		fallbackProtocol = "ip4"
	} else {
		fallbackProtocol = "ip6"
	}

	dialProtocol = module.TCP.Protocol
	if module.TCP.Protocol == "tcp" {
		target_address, _, err := net.SplitHostPort(target)
		ip, err := net.ResolveIPAddr(module.TCP.PreferredIpProtocol, target_address)
		if err != nil {
			ip, err = net.ResolveIPAddr(fallbackProtocol, target_address)
			if err != nil {
				return nil, err
			}
		}

		if ip.IP.To4() == nil {
			dialProtocol = "tcp6"
		} else {
			dialProtocol = "tcp4"
		}
	}

	if dialProtocol == "tcp6" {
		fmt.Fprintf(w, "probe_ip_protocol 6\n")
	} else {
		fmt.Fprintf(w, "probe_ip_protocol 4\n")
	}

	if !module.TCP.TLS {
		return dialer.Dial(dialProtocol, target)
	}
	config, err := module.TCP.TLSConfig.GenerateConfig()
	if err != nil {
		return nil, err
	}
	return tls.DialWithDialer(dialer, dialProtocol, target, config)
}
開發者ID:prometheus,項目名稱:blackbox_exporter,代碼行數:49,代碼來源:tcp.go

示例10: UnmarshalJSON

func (i *siNetIFInfo) UnmarshalJSON(data []byte) (err error) {
	var tmp struct {
		Metric      int    `json:"metric"`
		MTU         int    `json:"mtu"`
		Flags       int    `json:"flags"`
		Type        string `json:"type"`
		Name        string `json:"name"`
		Broadcast   string `json:"broadcast"`
		Address     string `json:"address"`
		Address6    string `json:"address6"`
		HWAddr      string `json:"hwaddr"`
		Destination string `json:"destination"`
		Netmask     string `json:"netmask"`
	}
	err = json.Unmarshal(data, &tmp)
	if err != nil {
		return
	}

	i.Metric = tmp.Metric
	i.MTU = tmp.MTU
	i.Flags = tmp.Flags
	i.Type = tmp.Type
	i.Name = tmp.Name

	i.Broadcast, err = net.ResolveIPAddr("ip", tmp.Broadcast)
	if err != nil {
		return
	}
	i.Address, err = net.ResolveIPAddr("ip", tmp.Address)
	if err != nil {
		return
	}
	i.Address6, err = net.ResolveIPAddr("ip", tmp.Address6)
	if err != nil {
		return
	}
	i.HWAddr, err = net.ParseMAC(tmp.HWAddr)
	if err != nil {
		return
	}
	i.Destination, err = net.ResolveIPAddr("ip", tmp.Destination)
	if err != nil {
		return
	}
	i.Netmask = net.IPMask(net.ParseIP(tmp.Netmask))
	return
}
開發者ID:shawnps,項目名稱:go-agent-endpoint,代碼行數:48,代碼來源:hostInfo.go

示例11: udpAddrFromString

func udpAddrFromString(addr string) *net.UDPAddr {
	host, portStr, err := net.SplitHostPort(addr)
	if err != nil {
		log.Fatal("Bad StatsD listening address", addr)
	}

	if host == "" {
		host = "0.0.0.0"
	}
	ip, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		log.Fatalf("Unable to resolve %s: %s", host, err)
	}

	port, err := strconv.Atoi(portStr)
	if err != nil || port < 0 || port > 65535 {
		log.Fatalf("Bad port %s: %s", portStr, err)
	}

	return &net.UDPAddr{
		IP:   ip.IP,
		Port: port,
		Zone: ip.Zone,
	}
}
開發者ID:Jimdo,項目名稱:statsd_exporter,代碼行數:25,代碼來源:main.go

示例12: ResolveIP

func (resolver *addressResolver) ResolveIP(host string) (net.IP, error) {
	if host == "localhost" || host == "127.0.0.1" {
		if resolver.local != nil {
			return resolver.local, nil
		}
		if !resolver.checked {
			resolver.checked = true
			devices, err := net.Interfaces()
			if err != nil {
				return nil, err
			}
			for _, dev := range devices {
				if (dev.Flags&net.FlagUp != 0) && (dev.Flags&net.FlagLoopback == 0) {
					addrs, err := dev.Addrs()
					if err != nil {
						continue
					}
					for i := range addrs {
						if ip, ok := addrs[i].(*net.IPNet); ok {
							log.Printf("Using %v for %s", ip, host)
							resolver.local = ip.IP
							return resolver.local, nil
						}
					}
				}
			}
		}
	}
	addr, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		return nil, err
	}
	return addr.IP, nil
}
開發者ID:hguemar,項目名稱:geard,代碼行數:34,代碼來源:support.go

示例13: receiveSynAck

func receiveSynAck(localAddress, remoteAddress string) time.Time {
	netaddr, err := net.ResolveIPAddr("ip4", localAddress)
	if err != nil {
		log.Fatalf("net.ResolveIPAddr: %s. %s\n", localAddress, netaddr)
	}

	conn, err := net.ListenIP("ip4:tcp", netaddr)
	if err != nil {
		log.Fatalf("ListenIP: %s\n", err)
	}
	var receiveTime time.Time
	for {
		buf := make([]byte, 1024)
		numRead, raddr, err := conn.ReadFrom(buf)
		if err != nil {
			log.Fatalf("ReadFrom: %s\n", err)
		}
		if raddr.String() != remoteAddress {
			// this is not the packet we are looking for
			continue
		}
		receiveTime = time.Now()
		//fmt.Printf("Received: % x\n", buf[:numRead])
		tcp := NewTCPHeader(buf[:numRead])
		// Closed port gets RST, open port gets SYN ACK
		if tcp.HasFlag(RST) || (tcp.HasFlag(SYN) && tcp.HasFlag(ACK)) {
			break
		}
	}
	return receiveTime
}
開發者ID:kelixin,項目名稱:latency,代碼行數:31,代碼來源:latency.go

示例14: NewPingChecker

// NewPingChecker returns a check function that can check if a host answer to a ICMP Ping
func NewPingChecker(host, service, ip string) CheckFunction {
	return func() Event {
		var retRtt time.Duration
		var result = Event{Host: host, Service: service, State: "critical"}

		p := fastping.NewPinger()
		p.MaxRTT = maxPingTime
		ra, err := net.ResolveIPAddr("ip4:icmp", ip)
		if err != nil {
			result.Description = err.Error()
		}

		p.AddIPAddr(ra)
		p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
			result.State = "ok"
			result.Metric = float32(retRtt.Nanoseconds() / 1e6)
		}

		err = p.Run()
		if err != nil {
			result.Description = err.Error()
		}
		return result
	}
}
開發者ID:albertogviana,項目名稱:gochecks,代碼行數:26,代碼來源:checks.go

示例15: Ping

func Ping(timeout int) {
	log.SetPrefix("[Ping] ")
	scanner := bufio.NewScanner(os.Stdin)

	ips := make([]string, 0)
	var input string
	// single ip
	for scanner.Scan() {
		input = scanner.Text()
		_, err := net.ResolveIPAddr("ip", input)
		if err != nil {
			break
		} else {
			ips = append(ips, input)
		}
	}
	// whole lan
	if strings.Contains(input, "/") {
		lastDotIdx := strings.LastIndex(input, ".")
		ipPre := input[:lastDotIdx+1]
		for i := 0; i < 256; i++ {
			ip := ipPre + strconv.Itoa(i)
			ips = append(ips, ip)
		}
	}

	runFastPing(ips, "", timeout)
	runFastPing(ips, "127.0.0.1", timeout)

}
開發者ID:Alwayswithme,項目名稱:go-netkits,代碼行數:30,代碼來源:fastping.go


注:本文中的net.ResolveIPAddr函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。