// PingOverIface sends an arp ping over interface 'iface' to 'dstIP'
769848
func PingOverIface(dstIP net.IP, iface net.Interface) (net.HardwareAddr, time.Duration, error) {
	if err := validateIP(dstIP); err != nil {
		return nil, 0, err
	}

	srcMac := iface.HardwareAddr
	srcIP, err := findIPInNetworkFromIface(dstIP, iface)
	if err != nil {
		return nil, 0, err
	}

	broadcastMac := []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
	request := newArpRequest(srcMac, srcIP, broadcastMac, dstIP)

	if err := initialize(iface); err != nil {
		return nil, 0, err
	}
	defer deinitialize()

	type PingResult struct {
		mac      net.HardwareAddr
		duration time.Duration
		err      error
	}
	pingResultChan := make(chan PingResult)

	go func() {
		// send arp request
		verboseLog.Printf("arping '%s' over interface: '%s' with address: '%s'\n", dstIP, iface.Name, srcIP)
		if sendTime, err := send(request); err != nil {
			pingResultChan <- PingResult{nil, 0, err}
		} else {
			for {
				// receive arp response
				response, receiveTime, err := receive()

				if err != nil {
					pingResultChan <- PingResult{nil, 0, err}
					return
				}

				if response.IsResponseOf(request) {
					duration := receiveTime.Sub(sendTime)
					verboseLog.Printf("process received arp: srcIP: '%s', srcMac: '%s'\n",
						response.SenderIP(), response.SenderMac())
					pingResultChan <- PingResult{response.SenderMac(), duration, err}
					return
				}

				verboseLog.Printf("ignore received arp: srcIP: '%s', srcMac: '%s'\n",
					response.SenderIP(), response.SenderMac())
			}
		}
	}()

	select {
	case pingResult := <-pingResultChan:
		return pingResult.mac, pingResult.duration, pingResult.err
	case <-time.After(timeout):
		return nil, 0, ErrTimeout
	}
}
487180
func (nc NetClass) parseNetClassIface(devicePath string) (*NetClassIface, error) {
	interfaceClass := NetClassIface{}
	interfaceElem := reflect.ValueOf(&interfaceClass).Elem()
	interfaceType := reflect.TypeOf(interfaceClass)

	//start from 1 - skip the Name field
	for i := 1; i < interfaceElem.NumField(); i++ {
		fieldType := interfaceType.Field(i)
		fieldValue := interfaceElem.Field(i)

		if fieldType.Tag.Get("fileName") == "" {
			panic(fmt.Errorf("field %s does not have a filename tag", fieldType.Name))
		}

		value, err := util.SysReadFile(devicePath + "/" + fieldType.Tag.Get("fileName"))

		if err != nil {
			if os.IsNotExist(err) || err.Error() == "operation not supported" || err.Error() == "invalid argument" {
				continue
			}
			return nil, fmt.Errorf("could not access file %s: %s", fieldType.Tag.Get("fileName"), err)
		}

		switch fieldValue.Kind() {
		case reflect.String:
			fieldValue.SetString(value)
		case reflect.Ptr:
			var int64ptr *int64
			switch fieldValue.Type() {
			case reflect.TypeOf(int64ptr):
				var intValue int64
				if strings.HasPrefix(value, "0x") {
					intValue, err = strconv.ParseInt(value[2:], 16, 64)
					if err != nil {
						return nil, fmt.Errorf("expected hex value for %s, got: %s", fieldType.Name, value)
					}
				} else {
					intValue, err = strconv.ParseInt(value, 10, 64)
					if err != nil {
						return nil, fmt.Errorf("expected Uint64 value for %s, got: %s", fieldType.Name, value)
					}
				}
				fieldValue.Set(reflect.ValueOf(&intValue))
			default:
				return nil, fmt.Errorf("unhandled pointer type %q", fieldValue.Type())
			}
		default:
			return nil, fmt.Errorf("unhandled type %q", fieldValue.Kind())
		}
	}

	return &interfaceClass, nil
}
1362541
func GetIfaceAddr(name string) (net.Addr, error) {
	iface, err := net.InterfaceByName(name)
	if err != nil {
		return nil, err
	}
	addrs, err := iface.Addrs()
	if err != nil {
		return nil, err
	}
	var addrs4 []net.Addr
	for _, addr := range addrs {
		ip := (addr.(*net.IPNet)).IP
		if ip4 := ip.To4(); len(ip4) == net.IPv4len {
			addrs4 = append(addrs4, addr)
		}
	}
	if len(addrs4) == 0 {
		return nil, ErrorNoIpv4
	}
	return addrs4[0], nil
}
1145784
func (n *Networking) GetForwardableNetHostIP() (net.IP, error) {
	net, err := n.GetForwardableNet()
	if err != nil {
		return nil, err
	}
	return net.runtime.HostIP, nil
}
247021
func ParseMonitorAddresses(addrs []string) ([]net.IP, error) {
	monIps := []net.IP{}

	var (
		host string
		err  error
	)

	for _, mon := range addrs {
		mon = strings.TrimSpace(mon)
		host = mon
		if hasPort(mon) {
			host, _, err = net.SplitHostPort(mon)
			if err != nil {
				return nil, err
			}
		}
		if strings.HasPrefix(host, "[") {
			// pull the host/IP out of the brackets
			host = strings.Trim(host, "[]")
		}
		ip := net.ParseIP(host)
		if ip != nil {
			monIps = append(monIps, ip)
		} else {
			ips, err := net.LookupIP(host)
			if err != nil {
				return nil, err
			}
			if len(ips) > 0 {
				monIps = append(monIps, ips...)
			}
		}
	}

	return monIps, nil
}
175285
func (e *V1Endpoint) Ping() (PingResult, error) {
	logrus.Debugf("attempting v1 ping for registry endpoint %s", e)

	if e.String() == IndexServer {
		// Skip the check, we know this one is valid
		// (and we never want to fallback to http in case of error)
		return PingResult{Standalone: false}, nil
	}

	req, err := http.NewRequest("GET", e.Path("_ping"), nil)
	if err != nil {
		return PingResult{Standalone: false}, err
	}

	resp, err := e.client.Do(req)
	if err != nil {
		return PingResult{Standalone: false}, err
	}

	defer resp.Body.Close()

	jsonString, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return PingResult{Standalone: false}, fmt.Errorf("error while reading the http response: %s", err)
	}

	// If the header is absent, we assume true for compatibility with earlier
	// versions of the registry. default to true
	info := PingResult{
		Standalone: true,
	}
	if err := json.Unmarshal(jsonString, &info); err != nil {
		logrus.Debugf("Error unmarshaling the _ping PingResult: %s", err)
		// don't stop here. Just assume sane defaults
	}
	if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" {
		logrus.Debugf("Registry version header: '%s'", hdr)
		info.Version = hdr
	}
	logrus.Debugf("PingResult.Version: %q", info.Version)

	standalone := resp.Header.Get("X-Docker-Registry-Standalone")
	logrus.Debugf("Registry standalone header: '%s'", standalone)
	// Accepted values are "true" (case-insensitive) and "1".
	if strings.EqualFold(standalone, "true") || standalone == "1" {
		info.Standalone = true
	} else if len(standalone) > 0 {
		// there is a header set, and it is not "true" or "1", so assume fails
		info.Standalone = false
	}
	logrus.Debugf("PingResult.Standalone: %t", info.Standalone)
	return info, nil
}
1277051
func SockaddrToTCPAddr(sa Sockaddr) *net.TCPAddr {
	ip, zone := SockaddrToIPAndZone(sa)
	switch sa := sa.(type) {
	case *SockaddrInet4:
		return &net.TCPAddr{IP: ip, Port: sa.Port}
	case *SockaddrInet6:
		return &net.TCPAddr{IP: ip, Port: sa.Port, Zone: zone}
	}
	return nil
}
589968
func ioctlAddToBridge(iface, master *net.Interface) error {
	return ifIoctBridge(iface, master, ioctlBrAddIf)
}
414538
func (n *netPackageConfigSource) InterfaceAddresses(name string) ([]net.Addr, error) {
	iface, err := net.InterfaceByName(name)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return iface.Addrs()
}
300049
func (c *ServicedCli) cmdServiceSetIP(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 3 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "set-ip")
		c.exit(1)
		return
	}

	if args[len(args)-1] == "--generate-bash-completion" {
		// CC-892: Disable bash completion after SERVICE_ID because possible matches
		// are unavailable outside the container.
		return
	}

	svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	var endpointName string
	if len(args) > 1 {
		endpointName = args[1]
	}

	var ipAddress string
	if len(args) > 2 {
		ipAddress = args[2]
	}

	if ctx.Int("port") < 1 {
		fmt.Printf("Please specify the valid port number.\n\n")
		cli.ShowCommandHelp(ctx, "set-ip")
		c.exit(1)
		return
	}

	if ctx.String("proto") == "" {
		fmt.Printf("Please specify port protocol.\n\n")
		cli.ShowCommandHelp(ctx, "set-ip")
		c.exit(1)
		return
	}

	cfg := api.IPConfig{
		ServiceID:    svc.ID,
		IPAddress:    ipAddress,
		Port:         uint16(ctx.Int("port")),
		Proto:        ctx.String("proto"),
		EndpointName: endpointName,
	}

	if err := c.driver.SetIP(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
	}
	return
}
756914
func (p *peer) pingHandler() {
	defer p.wg.Done()

	pingTicker := time.NewTicker(pingInterval)
	defer pingTicker.Stop()

	// TODO(roasbeef): make dynamic in order to create fake cover traffic
	const numPingBytes = 16

out:
	for {
		select {
		case <-pingTicker.C:
			p.queueMsg(lnwire.NewPing(numPingBytes), nil)
		case <-p.quit:
			break out
		}
	}
}
264661
func NewEllipse(tags core.TagSlice) (*Ellipse, error) {
	ellipse := new(Ellipse)

	// set default
	ellipse.MinorToMajorAxisRatio = 1.0
	ellipse.StartParameter = 0.0
	ellipse.EndParameter = 360.0
	ellipse.ExtrusionDirection = core.Point{X: 0.0, Y: 0.0, Z: 1.0}

	ellipse.InitBaseEntityParser()
	ellipse.Update(map[int]core.TypeParser{
		10:  core.NewFloatTypeParserToVar(&ellipse.Center.X),
		20:  core.NewFloatTypeParserToVar(&ellipse.Center.Y),
		30:  core.NewFloatTypeParserToVar(&ellipse.Center.Z),
		11:  core.NewFloatTypeParserToVar(&ellipse.MajorAxisEnd.X),
		21:  core.NewFloatTypeParserToVar(&ellipse.MajorAxisEnd.Y),
		31:  core.NewFloatTypeParserToVar(&ellipse.MajorAxisEnd.Z),
		210: core.NewFloatTypeParserToVar(&ellipse.ExtrusionDirection.X),
		220: core.NewFloatTypeParserToVar(&ellipse.ExtrusionDirection.Y),
		230: core.NewFloatTypeParserToVar(&ellipse.ExtrusionDirection.Z),
		40:  core.NewFloatTypeParserToVar(&ellipse.MinorToMajorAxisRatio),
		41:  core.NewFloatTypeParserToVar(&ellipse.StartParameter),
		42:  core.NewFloatTypeParserToVar(&ellipse.EndParameter),
	})

	err := ellipse.Parse(tags)
	return ellipse, err
}
461405
func GratuitousArpOverIfaceByName(srcIP net.IP, ifaceName string) error {
	if err := validateIP(srcIP); err != nil {
		return err
	}

	iface, err := net.InterfaceByName(ifaceName)
	if err != nil {
		return err
	}
	return GratuitousArpOverIface(srcIP, *iface)
}
92512
func iptablesCommonPortalArgs(destIP net.IP, addPhysicalInterfaceMatch bool, addDstLocalMatch bool, destPort int, protocol v1.Protocol, service proxy.ServicePortName) []string {
	// This list needs to include all fields as they are eventually spit out
	// by iptables-save.  This is because some systems do not support the
	// 'iptables -C' arg, and so fall back on parsing iptables-save output.
	// If this does not match, it will not pass the check.  For example:
	// adding the /32 on the destination IP arg is not strictly required,
	// but causes this list to not match the final iptables-save output.
	// This is fragile and I hope one day we can stop supporting such old
	// iptables versions.
	args := []string{
		"-m", "comment",
		"--comment", service.String(),
		"-p", strings.ToLower(string(protocol)),
		"-m", strings.ToLower(string(protocol)),
		"--dport", fmt.Sprintf("%d", destPort),
	}

	if destIP != nil {
		args = append(args, "-d", utilproxy.ToCIDR(destIP))
	}

	if addPhysicalInterfaceMatch {
		args = append(args, "-m", "physdev", "!", "--physdev-is-in")
	}

	if addDstLocalMatch {
		args = append(args, "-m", "addrtype", "--dst-type", "LOCAL")
	}

	return args
}
179636
func (s *Server) pingSweep() {
	responses := make(map[string]string, len(s.managedNodes))
	for k := range s.managedNodes {
		_, msg, err := s.managedNodes[k].Ping()
		if err != nil {
			responses[s.managedNodes[k].Address()] = err.Error()
			continue
		}
		responses[s.managedNodes[k].Address()] = msg
	}
}
73783
func (c *Client) PingEndpoint() error {
	_, err := c.Restapi.GetHello(nil)
	return err
}
898409
func (engine *Engine) PingContext(ctx context.Context) error {
	session := engine.NewSession()
	defer session.Close()
	return session.PingContext(ctx)
}