当前位置: 首页>>代码示例>>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;未经允许,请勿转载。