// DiscoverPMP attempts to scan the local network for a NAT-PMP enabled device
// within the given timeout.
512176
func DiscoverPMP(timeout time.Duration) (*PMP, error) {
	// Retrieve the gateway IP address of the local network.
	gatewayIP, err := gateway.DiscoverGateway()
	if err != nil {
		return nil, err
	}

	pmp := &PMP{
		client:         natpmp.NewClientWithTimeout(gatewayIP, timeout),
		forwardedPorts: make(map[uint16]struct{}),
	}

	// We'll then attempt to retrieve the external IP address of this
	// device to ensure it is not behind multiple NATs.
	if _, err := pmp.ExternalIP(); err != nil {
		return nil, err
	}

	return pmp, nil
}
922207
func (cfg *discoveryProcessConfig) NewDiscoveryProcess() *discoveryProcess {
	port := int(atomic.LoadInt32(&discoveryBasePort))
	atomic.AddInt32(&discoveryBasePort, 2)

	copied := *cfg
	copied.webPort = port
	copied.discoveryHost = fmt.Sprintf("http://localhost:%d", copied.webPort)

	return &discoveryProcess{cfg: &copied}
}
1163738
func (c *Client) DiscoverPacket() *dhcp4.Packet {
	packet := dhcp4.NewPacket(dhcp4.BootRequest)
	rand.Read(packet.TransactionID[:])
	packet.CHAddr = c.iface.Attrs().HardwareAddr
	packet.Broadcast = true

	packet.Options.Add(dhcp4.OptionDHCPMessageType, dhcp4opts.DHCPDiscover)
	packet.Options.Add(dhcp4.OptionMaximumDHCPMessageSize, dhcp4opts.Uint16(maxMessageSize))
	return packet
}
285877
func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
	return CommandLine.IPP(name, shorthand, value, usage)
}
79620
func (c *Client) Discover() (NATType, *Host, error) {
	if c.serverAddr == "" {
		c.SetServerAddr(DefaultServerAddr)
	}
	serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
	if err != nil {
		return NATError, nil, err
	}
	// Use the connection passed to the client if it is not nil, otherwise
	// create a connection and close it at the end.
	conn := c.conn
	if conn == nil {
		conn, err = net.ListenUDP("udp", nil)
		if err != nil {
			return NATError, nil, err
		}
		defer conn.Close()
	}
	return c.discover(conn, serverUDPAddr)
}
296102
func (f *NetworkFingerprint) findInterface(deviceName string) (*net.Interface, error) {
	// If we aren't given a device, look it up by using the interface with the default route
	if deviceName == "" {
		ri, err := sockaddr.NewRouteInfo()
		if err != nil {
			return nil, err
		}

		defaultIfName, err := ri.GetDefaultInterfaceName()
		if err != nil {
			return nil, err
		}
		if defaultIfName == "" {
			return nil, fmt.Errorf("no network_interface given and failed to determine interface attached to default route")
		}
		deviceName = defaultIfName
	}

	return f.interfaceDetector.InterfaceByName(deviceName)
}
352138
func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
	if dType != discoverapi.NodeDiscovery {
		return nil
	}
	notif := &api.DiscoveryNotification{
		DiscoveryType: dType,
		DiscoveryData: data,
	}
	return d.call("DiscoverNew", notif, &api.DiscoveryResponse{})
}
1334927
func GetMinimalIPNet(nw *net.IPNet) *net.IPNet {
	if nw == nil {
		return nil
	}
	if len(nw.IP) == 16 && nw.IP.To4() != nil {
		m := nw.Mask
		if len(m) == 16 {
			m = m[12:16]
		}
		return &net.IPNet{IP: nw.IP.To4(), Mask: m}
	}
	return nw
}
524630
func DialTimeoutLocal(socket string, timeout time.Duration) (net.Conn, error) {
	// on unix, we dial a unix socket
	return net.DialTimeout("unix", socket, timeout)
}
954093
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
	if c == nil {
		return nil
	}
	return c.DiscoveryClient
}
922441
func (s *MockDiscoveryServer) Discover(ctx context.Context, request *discovery.SignedRequest) (*discovery.Response, error) {
	if request == nil {
		return nil, errors.New("nil request")
	}

	req := &discovery.Request{}
	err := proto.Unmarshal(request.Payload, req)
	if err != nil {
		return nil, errors.Wrap(err, "failed parsing request")
	}
	if req.Authentication == nil {
		return nil, errors.New("access denied, no authentication info in request")
	}
	if len(req.Authentication.ClientIdentity) == 0 {
		return nil, errors.New("access denied, client identity wasn't supplied")
	}

	var results []*discovery.QueryResult
	for _, q := range req.Queries {
		result := s.processQuery(q)
		if result != nil {
			results = append(results, result)
		}
	}
	return &discovery.Response{
		Results: results,
	}, nil
}
828945
func (n *Network) DiscoveredPeer(p *Peer, chaincodes ...string) DiscoveredPeer {
	peerCert, err := ioutil.ReadFile(n.PeerCert(p))
	Expect(err).NotTo(HaveOccurred())

	return DiscoveredPeer{
		MSPID:      n.Organization(p.Organization).MSPID,
		Endpoint:   fmt.Sprintf("127.0.0.1:%d", n.PeerPort(p, ListenPort)),
		Identity:   string(peerCert),
		Chaincodes: chaincodes,
	}
}
771179
func (a *Astilectron) watchNoAccept(timeout time.Duration, chanAccepted chan bool) {
	//check timeout
	if timeout == 0 {
		timeout = DefaultAcceptTCPTimeout
	}
	var t = time.NewTimer(timeout)
	defer t.Stop()
	for {
		select {
		case <-chanAccepted:
			return
		case <-t.C:
			astilog.Errorf("No TCP connection has been accepted in the past %s", timeout)
			a.dispatcher.dispatch(Event{Name: EventNameAppNoAccept, TargetID: targetIDApp})
			a.dispatcher.dispatch(Event{Name: EventNameAppCmdStop, TargetID: targetIDApp})
			return
		}
	}
}
1045604
func (c *EndpointConfig) peerMSPID(name string) (string, bool) {
	var mspID string
	// Find organisation/msp that peer belongs to
	for _, org := range c.networkConfig.Organizations {
		for i := 0; i < len(org.Peers); i++ {
			if strings.EqualFold(org.Peers[i], name) {
				// peer belongs to this org add org msp
				mspID = org.MSPID
				break
			} else {
				peer, ok := c.findMatchingPeer(org.Peers[i])
				if ok && strings.EqualFold(peer, name) {
					mspID = org.MSPID
					break
				}
			}
		}
	}

	return mspID, mspID != ""
}
732431
func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target encPubkey) ([]*node, error) {
	// If we haven't seen a ping from the destination node for a while, it won't remember
	// our endpoint proof and reject findnode. Solicit a ping first.
	if time.Since(t.db.LastPingReceived(toid, toaddr.IP)) > bondExpiration {
		<-t.sendPing(toid, toaddr, nil)
		// Wait for them to ping back and process our pong.
		time.Sleep(respTimeout)
	}

	// Add a matcher for 'neighbours' replies to the pending reply queue. The matcher is
	// active until enough nodes have been received.
	nodes := make([]*node, 0, bucketSize)
	nreceived := 0
	errc := t.pending(toid, toaddr.IP, p_neighborsV4, func(r interface{}) (matched bool, requestDone bool) {
		reply := r.(*neighborsV4)
		for _, rn := range reply.Nodes {
			nreceived++
			n, err := t.nodeFromRPC(toaddr, rn)
			if err != nil {
				t.log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err)
				continue
			}
			nodes = append(nodes, n)
		}
		return true, nreceived >= bucketSize
	})
	t.send(toaddr, toid, p_findnodeV4, &findnodeV4{
		Target:     target,
		Expiration: uint64(time.Now().Add(expiration).Unix()),
	})
	return nodes, <-errc
}
697412
func (c *Client) DiscoverOffer() (*dhcp4.Packet, error) {
	ctx, cancel := context.WithCancel(context.Background())
	wg, out, errCh := c.SimpleSendAndRead(ctx, DefaultServers, c.DiscoverPacket())
	defer func() {
		// Explicitly cancel first, then wait.
		cancel()
		wg.Wait()
	}()

	for packet := range out {
		msgType := dhcp4opts.GetDHCPMessageType(packet.Packet.Options)
		if msgType == dhcp4opts.DHCPOffer {
			// Deferred cancel will cancel the goroutine.
			return packet.Packet, nil
		}
	}

	if err, ok := <-errCh; ok && err != nil {
		return nil, err
	}
	return nil, fmt.Errorf("didn't get a packet")
}
787432
func (l *LibcontainerBackend) discoverdDial(network, addr string) (net.Conn, error) {
	host, _, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, err
	}
	if strings.HasSuffix(host, ".discoverd") {
		// ensure discoverd is configured
		<-l.discoverdConfigured
		// lookup the service and pick a random address
		service := strings.TrimSuffix(host, ".discoverd")
		addrs, err := l.discoverdClient.Service(service).Addrs()
		if err != nil {
			return nil, err
		} else if len(addrs) == 0 {
			return nil, fmt.Errorf("lookup %s: no such host", host)
		}
		addr = addrs[random.Math.Intn(len(addrs))]
	}
	return dialer.Default.Dial(network, addr)
}