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


Golang IPAddr.String方法代码示例

本文整理汇总了Golang中net.IPAddr.String方法的典型用法代码示例。如果您正苦于以下问题:Golang IPAddr.String方法的具体用法?Golang IPAddr.String怎么用?Golang IPAddr.String使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net.IPAddr的用法示例。


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

示例1: sendPing

func sendPing(conn *net.IPConn, addr *net.IPAddr, id, seq int) {
	bytes, err := (&icmpMessage{
		Type: icmpv4EchoRequest, Code: 0,
		Body: &icmpEcho{
			ID: id, Seq: seq,
			Data: timeToBytes(time.Now()),
		},
	}).Marshal()
	if err != nil {
		panic(err)
	}

	for {
		if _, _, err := conn.WriteMsgIP(bytes, nil, addr); err != nil {
			if neterr, ok := err.(*net.OpError); ok {
				if neterr.Err == syscall.ENOBUFS {
					// creating a busy loop?
					continue
				}
			}
		}
		fmt.Printf("ICMP: Ping sent: %s, id=%d.\n", addr.String(), id)
		break
	}
}
开发者ID:mehulsbhatt,项目名称:pinger-2,代码行数:25,代码来源:icmp.go

示例2: ReturnFloatingIP

func (cloud *OpenStack) ReturnFloatingIP(addr net.IPAddr) error {
	// grab the address out of the used
	index := indexOfAddress(cloud.usedIPs, addr)
	if index == -1 {
		return errors.New(fmt.Sprintf("'%s' address was not previously allocated", addr.String()))
	}

	// mutex
	cloud.mutex.Lock()

	// remove from usedIPs
	cloud.usedIPs = cloud.usedIPs[:index+copy(cloud.usedIPs[index:], cloud.usedIPs[index+1:])]

	// recreate the availableIPs slice if it was set to nil
	if cloud.availableIps == nil {
		cloud.availableIps = make([]net.IPAddr, 0)
	}

	// add the address to available
	cloud.availableIps = append(cloud.availableIps, addr)

	// mutex
	cloud.mutex.Unlock()

	return nil
}
开发者ID:timepieces141,项目名称:code-examples,代码行数:26,代码来源:IP-Manipulation.go

示例3: AddIPAddr

// AddIPAddr adds an IP address to Pinger. ip arg should be a net.IPAddr
// pointer.
func (p *Pinger) AddIPAddr(ip *net.IPAddr) {
	p.addrs[ip.String()] = ip
	if isIPv4(ip.IP) {
		p.hasIPv4 = true
	} else if isIPv6(ip.IP) {
		p.hasIPv6 = true
	}
}
开发者ID:kanocz,项目名称:go-fastping,代码行数:10,代码来源:fastping.go

示例4: ReverseLookup

func ReverseLookup(ip net.IPAddr) (name string, err error) {
	names, err := net.LookupAddr(ip.String())
	if err == nil && len(names) > 0 {
		name = names[0]
		// names seem to have a . at the end. remove it
		if name[len(name)-1] == '.' {
			name = name[:len(name)-1]
		}
	}
	return
}
开发者ID:simulatedsimian,项目名称:tracetcp-go,代码行数:11,代码来源:utils.go

示例5: SetIPAddr

// SetIPAddr sets the ip address of the target host.
func (p *Pinger) SetIPAddr(ipaddr *net.IPAddr) {
	var ipv4 bool
	if isIPv4(ipaddr.IP) {
		ipv4 = true
	} else if isIPv6(ipaddr.IP) {
		ipv4 = false
	}

	p.ipaddr = ipaddr
	p.addr = ipaddr.String()
	p.ipv4 = ipv4
}
开发者ID:sparrc,项目名称:go-ping,代码行数:13,代码来源:ping.go

示例6: onRecv

func (state *State) onRecv(addr *net.IPAddr, rtt time.Duration) {
	s := state.PingSessions[addr.String()]

	s.Lock()
	s.TotalRTT += rtt
	s.PingCount++
	if s.PingCount > state.PingChecker.PingLimit {
		state.Pinger.RemoveIPAddr(addr)
	}
	s.Unlock()

	return
}
开发者ID:bsdlp,项目名称:matchmaking,代码行数:13,代码来源:latency.go

示例7: ping

func ping(host string, ra *net.IPAddr, rtt time.Duration, c chan bool, lock *sync.RWMutex, store map[string]*HostStore) {
	p := fastping.NewPinger()

	results := make(map[string]*response)
	results[ra.String()] = nil
	p.AddIPAddr(ra)

	onRecv, onIdle := make(chan *response), make(chan bool)
	p.AddHandler("receive", func(addr *net.IPAddr, t time.Duration) {
		onRecv <- &response{addr: addr, rtt: t}
	})
	p.AddHandler("idle", func() {
		onIdle <- true
	})

	p.MaxRTT = rtt
	quit, errch := p.RunLoop()

	wait := make(chan bool)

loop:
	for {
		select {
		case <-c:
			log.Printf("get interrupted %v", ra)
			quit <- wait
		case res := <-onRecv:
			if _, ok := results[res.addr.String()]; ok {
				results[res.addr.String()] = res
			}
		case <-onIdle:
			for v, r := range results {
				lock.Lock()
				if r == nil {
					store[host].Insert(0)
				} else {
					store[host].Insert(r.rtt)
				}
				lock.Unlock()
				results[v] = nil
			}
		case err := <-errch:
			log.Println("%v failed: %v", ra, err)
			c <- true
		case <-wait:
			break loop
		}
	}
	log.Printf("exit %v", ra)
}
开发者ID:hizel,项目名称:pingd,代码行数:50,代码来源:ping.go

示例8: initiator

// Bootstrap message initiator retrieving possible peer addresses from various
// seed generators and sending bootstrap requests at a given rate.
func (b *Bootstrapper) initiator() {
	b.log.Info("starting initiator")

	// Repeat message initiation until termination is requested
	var errc chan error
	for errc == nil {
		// Retrieve a possible seed address from a random algorithm
		var addr *net.IPAddr
		select {
		// Short circuit termination request
		case errc = <-b.quit:
			continue

		default:
			select {
			case addr = <-b.scanSink:
			case addr = <-b.probeSink:
			case addr = <-b.coreOSSink:
			case errc = <-b.quit:
				continue
			}
		}
		// Discard self addresses
		self := 0
		if b.ipnet.IP.String() == addr.IP.String() {
			self = b.addr.Port
		}
		// Send a bootstrap request on all configured ports
		for _, port := range config.BootPorts {
			if port == self {
				continue
			}
			host := net.JoinHostPort(addr.String(), strconv.Itoa(port))

			addr, err := net.ResolveUDPAddr("udp", host)
			if err != nil {
				panic(fmt.Sprintf("failed to resolve remote bootstrapper (%v): %v.", host, err))
			}
			b.sock.WriteToUDP(b.request, addr)
		}
		time.Sleep(100 * time.Millisecond)
	}
	// Report termination and sync closer
	b.log.Info("terminating initiator")
	errc <- nil
}
开发者ID:simia-tech,项目名称:iris,代码行数:48,代码来源:bootstrap.go

示例9: testScanSeeder

// Tests that the scanning ad-hoc seeder indeed generates IP addresses in the
// correct order and range for a specific ipnet configuration.
func testScanSeeder(t *testing.T, subnet int, addr *net.IPAddr) {
	// Create the IP net from the configurations
	ipnet := &net.IPNet{
		IP:   addr.IP,
		Mask: net.CIDRMask(subnet, 32),
	}
	// Create the scanning seed generator, address sink and boot it
	seeder := newScanSeeder(ipnet, log15.New("ipnet", ipnet))
	sink, phase := make(chan *net.IPAddr), uint32(0)

	if err := seeder.Start(sink, &phase); err != nil {
		t.Fatalf("failed to start seed generator: %v.", err)
	}
	// Retrieve twice the possible host count, ensuring they are in range
	valid := (1 << uint(32-subnet)) - 2
	addrs := make(map[string]int)
	for i := 0; i < 2*valid; i++ {
		select {
		case addr := <-sink:
			if !ipnet.Contains(addr.IP) {
				t.Fatalf("out of range address generated: %v.", addr)
			}
			addrs[addr.String()]++
		case <-time.After(time.Second):
			t.Fatalf("failed to retrieve next address")
		}
	}
	// Verify that enough hosts were returned and the right multiplier
	if len(addrs) != valid {
		t.Fatalf("address variation mismatch: have %v, want %v.", len(addrs), valid)
	}
	for _, count := range addrs {
		if count != 2 {
			t.Fatalf("address generation count mismatch: have %v, want %v.", count, 2)
		}
	}
	// Terminate the generator
	if err := seeder.Close(); err != nil {
		t.Fatalf("failed to terminate seed generator: %v.", err)
	}
}
开发者ID:simia-tech,项目名称:iris,代码行数:43,代码来源:scan_test.go

示例10: testProbeSeeder

// Tests that the probing ad-hoc seeder indeed generates IP addresses in the
// correct range for a specific ipnet configuration.
func testProbeSeeder(t *testing.T, subnet int, addr *net.IPAddr) {
	// Create the IP net from the configurations
	ipnet := &net.IPNet{
		IP:   addr.IP,
		Mask: net.CIDRMask(subnet, 32),
	}
	// Create the probing seed generator, address sink and boot it
	seeder := newProbeSeeder(ipnet, log15.New("ipnet", ipnet))
	sink, phase := make(chan *net.IPAddr), uint32(0)

	if err := seeder.Start(sink, &phase); err != nil {
		t.Fatalf("failed to start seed generator: %v.", err)
	}
	// Retrieve a large batch of random addresses, ensuring they are in range
	iters := 100000
	addrs := make(map[string]int)
	for i := 0; i < iters; i++ {
		select {
		case addr := <-sink:
			if !ipnet.Contains(addr.IP) {
				t.Fatalf("out of range address generated: %v.", addr)
			}
			addrs[addr.String()]++
		case <-time.After(time.Second):
			t.Fatalf("failed to retrieve next address")
		}
	}
	// Verify that multipliers are within expected range
	for _, count := range addrs {
		lo := (iters / ((1 << uint(32-subnet)) - 2)) / 10 * 5
		hi := (iters / ((1 << uint(32-subnet)) - 2)) / 10 * 15
		if lo > count || count > hi {
			t.Fatalf("non uniform address count: have %v, want in [%v-%v].", count, lo, hi)
		}
	}
	// Terminate the generator
	if err := seeder.Close(); err != nil {
		t.Fatalf("failed to terminate seed generator: %v.", err)
	}
}
开发者ID:simia-tech,项目名称:iris,代码行数:42,代码来源:probe_test.go

示例11: Ping

func Ping(addr *net.IPAddr, duration time.Duration) *time.Duration {
	reply := make(chan *time.Duration, 3)
	pingChan <- PingJob{
		Reply:    reply,
		Addr:     addr,
		Deadline: time.Now().Add(duration),
	}
	select {
	case rtt := <-reply:
		if rtt == nil {
			fmt.Printf("Ping: %s: got timeout.\n", addr.String())
		} else {
			fmt.Printf("Ping: %s: %s.\n", addr.String(), rtt)
		}
		return rtt
	case <-time.After(duration):
		fmt.Printf("Ping: %s: no reply.\n", addr.String())
		return nil
	}
}
开发者ID:mehulsbhatt,项目名称:pinger-2,代码行数:20,代码来源:ping.go

示例12: procRecv

func (p *Pinger) procRecv(recv *packet, queue map[string]*net.IPAddr) {
	var ipaddr *net.IPAddr
	switch adr := recv.addr.(type) {
	case *net.IPAddr:
		ipaddr = adr
	case *net.UDPAddr:
		ipaddr = &net.IPAddr{IP: adr.IP, Zone: adr.Zone}
	default:
		return
	}

	addr := ipaddr.String()
	p.mu.Lock()
	if _, ok := p.addrs[addr]; !ok {
		p.mu.Unlock()
		return
	}
	p.mu.Unlock()

	var bytes []byte
	var proto int
	if isIPv4(ipaddr.IP) {
		if p.network == "ip" {
			bytes = ipv4Payload(recv.bytes)
		} else {
			bytes = recv.bytes
		}
		proto = ProtocolICMP
	} else if isIPv6(ipaddr.IP) {
		bytes = recv.bytes
		proto = ProtocolIPv6ICMP
	} else {
		return
	}

	var m *icmp.Message
	var err error
	if m, err = icmp.ParseMessage(proto, bytes); err != nil {
		return
	}

	if m.Type != ipv4.ICMPTypeEchoReply && m.Type != ipv6.ICMPTypeEchoReply {
		return
	}

	var rtt time.Duration
	switch pkt := m.Body.(type) {
	case *icmp.Echo:
		p.mu.Lock()
		if pkt.ID == p.id && pkt.Seq == p.seq {
			rtt = time.Since(bytesToTime(pkt.Data[:TimeSliceLength]))
		}
		p.mu.Unlock()
	default:
		return
	}

	if _, ok := queue[addr]; ok {
		delete(queue, addr)
		p.mu.Lock()
		handler := p.OnRecv
		p.mu.Unlock()
		if handler != nil {
			handler(ipaddr, rtt)
		}
	}
}
开发者ID:bsdlp,项目名称:go-fastping,代码行数:67,代码来源:fastping.go

示例13: RemoveIPAddr

// RemoveIPAddr removes an IP address from Pinger. ip arg should be a net.IPAddr
// pointer.
func (p *Pinger) RemoveIPAddr(ip *net.IPAddr) {
	p.mu.Lock()
	delete(p.addrs, ip.String())
	p.mu.Unlock()
}
开发者ID:bsdlp,项目名称:go-fastping,代码行数:7,代码来源:fastping.go

示例14: Addr2Name

func (p *Pingbeat) Addr2Name(addr *net.IPAddr) (string, string) {
	var name, tag string
	if _, found := p.ipv4targets[addr.String()]; found {
		name = p.ipv4targets[addr.String()][0]
		tag = p.ipv4targets[addr.String()][1]
	} else if _, found := p.ipv6targets[addr.String()]; found {
		name = p.ipv6targets[addr.String()][0]
		tag = p.ipv6targets[addr.String()][1]
	} else {
		logp.Err("Error: %s not found in Pingbeat targets!", addr.String())
		name = "err"
		tag = "err"
	}
	return name, tag
}
开发者ID:sreev,项目名称:pingbeat,代码行数:15,代码来源:pingbeat.go

示例15: updateNamespaceNetworkLinks

func updateNamespaceNetworkLinks(name string, sourceAddr *net.IPAddr, ports io.Reader) error {

	// Enable routing in the namespace
	output, err := exec.Command("ip", "netns", "exec", name, "sysctl", "-w", "net.ipv4.conf.all.route_localnet=1").Output()
	if err != nil {
		log.Printf("gear: Failed to enable localnet routing: %v", err)
		log.Printf("gear: error output: %v", output)
		return err
	}

	// Enable ip forwarding
	output, err = exec.Command("ip", "netns", "exec", name, "sysctl", "-w", "net.ipv4.ip_forward=1").Output()
	if err != nil {
		log.Printf("gear: Failed to enable ipv4 forwarding: %v", err)
		log.Printf("gear: error output: %v", output)
		return err
	}

	// Restore a set of rules to the table
	cmd := exec.Command("ip", "netns", "exec", name, "iptables-restore")
	stdin, errp := cmd.StdinPipe()
	if errp != nil {
		log.Printf("gear: Could not open pipe to iptables-restore: %v", errp)
		return errp
	}
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	defer stdin.Close()
	if err := cmd.Start(); err != nil {
		log.Printf("gear: Could not start iptables-restore: %v", errp)
		return err
	}

	fmt.Fprintf(stdin, "*nat\n")
	for {
		link := containers.NetworkLink{}
		if _, err := fmt.Fscanf(ports, "%s\t%v\t%v\t%s\n", &link.FromHost, &link.FromPort, &link.ToPort, &link.ToHost); err != nil {
			if err == io.EOF {
				break
			}
			log.Printf("gear: Could not read from network links file: %v", err)
			continue
		}
		if err := link.Check(); err != nil {
			log.Printf("gear: Link in file is not valid: %v", err)
			continue
		}
		if link.Complete() {
			srcIP, err := net.ResolveIPAddr("ip", link.FromHost)
			if err != nil {
				log.Printf("gear: Link source host does not resolve %v", err)
				continue
			}

			destIP, err := resolver.ResolveIP(link.ToHost)
			if err != nil {
				log.Printf("gear: Link destination host does not resolve %v", err)
				continue
			}

			log.Printf("Mapping %s(%s):%d -> %s:%d", sourceAddr.String(), srcIP.String(), link.FromPort, destIP.String(), link.ToPort)

			data := OutboundNetworkIptables{sourceAddr.String(), srcIP.IP.String(), link.FromPort, destIP.String(), link.ToPort}
			if err := OutboundNetworkIptablesTemplate.Execute(stdin, &data); err != nil {
				log.Printf("gear: Unable to write network link rules: %v", err)
				return err
			}
		}
	}
	fmt.Fprintf(stdin, "COMMIT\n")

	stdin.Close()
	if err := cmd.Wait(); err != nil {
		log.Printf("gear: iptables-restore did not successfully complete: %v", err)
		return err
	}
	return nil
}
开发者ID:jcantrill,项目名称:geard,代码行数:78,代码来源:cmd.go


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