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


Golang net.IPAddr类代码示例

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


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

示例1: ResolveIPAddr

func (ipad Net) ResolveIPAddr(p string, a string) (*net.IPAddr, error) {
	var i net.IPAddr
	i.Zone = "france"
	i.IP = net.ParseIP("localhost")
	ptr := &i
	return ptr, nil
}
开发者ID:pronebel,项目名称:uptime-1,代码行数:7,代码来源:PingPoller_test.go

示例2: 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

示例3: 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

示例4: 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

示例5: 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

示例6: 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

示例7: 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

示例8: 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

示例9: 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

示例10: 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

示例11: 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

示例12: 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

示例13: sendEchoRequest

func (l *icmpLoop) sendEchoRequest(addr *net.IPAddr) (*requestContext, error) {
	var conn *icmp.PacketConn
	var proto int
	var typ icmp.Type

	if l == nil {
		panic("icmp loop not initialized")
	}

	if isIPv4(addr.IP) {
		conn = l.conn4
		proto = protocolICMP
		typ = ipv4.ICMPTypeEcho
	} else if isIPv6(addr.IP) {
		conn = l.conn6
		proto = protocolIPv6ICMP
		typ = ipv6.ICMPTypeEchoRequest
	} else {
		return nil, fmt.Errorf("%v is unknown ip address", addr)
	}

	id := requestID{
		addr:  addr.String(),
		proto: proto,
		id:    rand.Intn(0xffff),
		seq:   rand.Intn(0xffff),
	}

	ctx := &requestContext{
		l:      l,
		id:     id,
		result: make(chan requestResult, 1),
	}

	l.mutex.Lock()
	l.requests[id] = ctx
	l.mutex.Unlock()

	payloadBuf := make([]byte, 0, 8)
	payload := bytes.NewBuffer(payloadBuf)
	ts := time.Now()
	binary.Write(payload, binary.BigEndian, ts.UnixNano())

	msg := &icmp.Message{
		Type: typ,
		Body: &icmp.Echo{
			ID:   id.id,
			Seq:  id.seq,
			Data: payload.Bytes(),
		},
	}
	encoded, _ := msg.Marshal(nil)

	_, err := conn.WriteTo(encoded, addr)
	if err != nil {
		return nil, err
	}

	ctx.ts = ts
	return ctx, nil
}
开发者ID:andrewkroh,项目名称:beats,代码行数:61,代码来源:loop.go

示例14: ExamplePacketConn_tracingIPPacketRoute

func ExamplePacketConn_tracingIPPacketRoute() {
	// Tracing an IP packet route to www.google.com.

	const host = "www.google.com"
	ips, err := net.LookupIP(host)
	if err != nil {
		log.Fatal(err)
	}
	var dst net.IPAddr
	for _, ip := range ips {
		if ip.To4() != nil {
			dst.IP = ip
			fmt.Printf("using %v for tracing an IP packet route to %s\n", dst.IP, host)
			break
		}
	}
	if dst.IP == nil {
		log.Fatal("no A record found")
	}

	c, err := net.ListenPacket(fmt.Sprintf("ip4:%d", iana.ProtocolICMP), "0.0.0.0") // ICMP for IPv4
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	p := ipv4.NewPacketConn(c)

	if err := p.SetControlMessage(ipv4.FlagTTL|ipv4.FlagSrc|ipv4.FlagDst|ipv4.FlagInterface, true); err != nil {
		log.Fatal(err)
	}
	wm := icmp.Message{
		Type: ipv4.ICMPTypeEcho, Code: 0,
		Body: &icmp.Echo{
			ID:   os.Getpid() & 0xffff,
			Data: []byte("HELLO-R-U-THERE"),
		},
	}

	rb := make([]byte, 1500)
	for i := 1; i <= 64; i++ { // up to 64 hops
		wm.Body.(*icmp.Echo).Seq = i
		wb, err := wm.Marshal(nil)
		if err != nil {
			log.Fatal(err)
		}
		if err := p.SetTTL(i); err != nil {
			log.Fatal(err)
		}

		// In the real world usually there are several
		// multiple traffic-engineered paths for each hop.
		// You may need to probe a few times to each hop.
		begin := time.Now()
		if _, err := p.WriteTo(wb, nil, &dst); err != nil {
			log.Fatal(err)
		}
		if err := p.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil {
			log.Fatal(err)
		}
		n, cm, peer, err := p.ReadFrom(rb)
		if err != nil {
			if err, ok := err.(net.Error); ok && err.Timeout() {
				fmt.Printf("%v\t*\n", i)
				continue
			}
			log.Fatal(err)
		}
		rm, err := icmp.ParseMessage(iana.ProtocolICMP, rb[:n])
		if err != nil {
			log.Fatal(err)
		}
		rtt := time.Since(begin)

		// In the real world you need to determine whether the
		// received message is yours using ControlMessage.Src,
		// ControlMessage.Dst, icmp.Echo.ID and icmp.Echo.Seq.
		switch rm.Type {
		case ipv4.ICMPTypeTimeExceeded:
			names, _ := net.LookupAddr(peer.String())
			fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, cm)
		case ipv4.ICMPTypeEchoReply:
			names, _ := net.LookupAddr(peer.String())
			fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, cm)
			return
		default:
			log.Printf("unknown ICMP message: %+v\n", rm)
		}
	}
}
开发者ID:musha68k,项目名称:go-ipfs,代码行数:89,代码来源:example_test.go

示例15: 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


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