本文整理汇总了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
}
}
示例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
}
示例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
}
}
示例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
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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)
}
}
示例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)
}
}
示例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
}
}
示例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)
}
}
}
示例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()
}
示例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
}
示例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
}