// ContainsIpAddress performs a binary search on the networkList to
// find a network containing the candidate IP address.
func (list networkList) ContainsIpAddress(addr net.IP) bool {

	// Search criteria
	//
	// The following conditions are satisfied when address_IP is in the network:
	// 1. address_IP ^ network_mask == network_IP ^ network_mask
	// 2. address_IP >= network_IP.
	// We are also assuming that network ranges do not overlap.
	//
	// For an ascending array of networks, the sort.Search returns the smallest
	// index idx for which condition network_IP > address_IP is satisfied, so we
	// are checking whether or not adrress_IP belongs to the network[idx-1].

	// Edge conditions check
	//
	// idx == 0 means that address_IP is  lesser than the first (smallest) network_IP
	// thus never satisfies search condition 2.
	// idx == array_length means that address_IP is larger than the last (largest)
	// network_IP so we need to check the last element for condition 1.

	addrValue := binary.BigEndian.Uint32(addr.To4())
	index := sort.Search(len(list), func(i int) bool {
		networkValue := binary.BigEndian.Uint32(list[i].IP)
		return networkValue > addrValue
	})
	return index > 0 && list[index-1].IP.Equal(addr.Mask(list[index-1].Mask))
}
示例#2
0
// getDNSRecordTypeByIP returns the DNS record type for the given IP.
// It will return "A" for an IPv4 address and "AAAA" for an IPv6 address.
func getDNSRecordTypeByIP(ip net.IP) string {
	if ip.To4() == nil {
		return "AAAA"
	}

	return "A"
}
示例#3
0
// GetPrivateIP returns the first private IP address found in a list of
// addresses.
func GetPrivateIP(addresses []net.Addr) (net.IP, error) {
	var candidates []net.IP

	// Find private IPv4 address
	for _, rawAddr := range addresses {
		var ip net.IP
		switch addr := rawAddr.(type) {
		case *net.IPAddr:
			ip = addr.IP
		case *net.IPNet:
			ip = addr.IP
		default:
			continue
		}

		if ip.To4() == nil {
			continue
		}
		if !IsPrivateIP(ip.String()) {
			continue
		}
		candidates = append(candidates, ip)
	}
	numIps := len(candidates)
	switch numIps {
	case 0:
		return nil, fmt.Errorf("No private IP address found")
	case 1:
		return candidates[0], nil
	default:
		return nil, fmt.Errorf("Multiple private IPs found. Please configure one.")
	}
}
示例#4
0
// GetPrivateIP is used to return the first private IP address
// associated with an interface on the machine
func GetPrivateIP() (net.IP, error) {
	addresses, err := net.InterfaceAddrs()
	if err != nil {
		return nil, fmt.Errorf("Failed to get interface addresses: %v", err)
	}

	// Find private IPv4 address
	for _, rawAddr := range addresses {
		var ip net.IP
		switch addr := rawAddr.(type) {
		case *net.IPAddr:
			ip = addr.IP
		case *net.IPNet:
			ip = addr.IP
		default:
			continue
		}

		if ip.To4() == nil {
			continue
		}
		if !isPrivateIP(ip.String()) {
			continue
		}

		return ip, nil
	}

	return nil, fmt.Errorf("No private IP address found")
}
示例#5
0
// Gets the ipv4 addr for a network interface
func (f *NetworkFingerprint) ipAddress(intf *net.Interface) (string, error) {
	var addrs []net.Addr
	var err error

	if addrs, err = f.interfaceDetector.Addrs(intf); err != nil {
		return "", err
	}

	if len(addrs) == 0 {
		return "", errors.New(fmt.Sprintf("Interface %s has no IP address", intf.Name))
	}
	for _, addr := range addrs {
		var ip net.IP
		switch v := (addr).(type) {
		case *net.IPNet:
			ip = v.IP
		case *net.IPAddr:
			ip = v.IP
		}
		if ip.To4() != nil {
			return ip.String(), nil
		}
	}

	return "", fmt.Errorf("Couldn't parse IP address for interface %s", intf.Name)

}
示例#6
0
// bigForIP creates a big.Int based on the provided net.IP
func bigForIP(ip net.IP) *big.Int {
	b := ip.To4()
	if b == nil {
		b = ip.To16()
	}
	return big.NewInt(0).SetBytes(b)
}
示例#7
0
文件: flags.go 项目: jeffweiss/snap
func getIP() string {
	ifaces, err := net.Interfaces()
	if err != nil {
		logger.WithField("_block", "getIP").Error(err)
		return "127.0.0.1"
	}
	for _, i := range ifaces {
		addrs, err := i.Addrs()
		if err != nil {
			logger.WithField("_block", "getIP").Error(err)
			return "127.0.0.1"
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPAddr:
				ip = v.IP
			case *net.IPNet:
				ip = v.IP
			}
			if ip == nil || ip.IsLoopback() {
				continue
			}
			ip = ip.To4()
			if ip == nil {
				continue // not an ipv4 address
			}
			return ip.String()
		}
	}
	return "127.0.0.1"
}
示例#8
0
文件: common.go 项目: ttaanngg/gobgp
func checkAddressFamily(ip net.IP) (*api.AddressFamily, error) {
	var rf *api.AddressFamily
	var e error
	switch subOpts.AddressFamily {
	case "ipv4", "v4", "4":
		rf = api.AF_IPV4_UC
	case "ipv6", "v6", "6":
		rf = api.AF_IPV6_UC
	case "vpnv4", "vpn-ipv4":
		rf = api.AF_IPV4_VPN
	case "vpnv6", "vpn-ipv6":
		rf = api.AF_IPV6_VPN
	case "evpn":
		rf = api.AF_EVPN
	case "encap":
		rf = api.AF_ENCAP
	case "rtc":
		rf = api.AF_RTC
	case "":
		if len(ip) == 0 || ip.To4() != nil {
			rf = api.AF_IPV4_UC
		} else {
			rf = api.AF_IPV6_UC
		}
	default:
		e = fmt.Errorf("unsupported address family: %s", subOpts.AddressFamily)
	}
	return rf, e
}
示例#9
0
// Release allows releasing the address from the specified address space
func (a *Allocator) Release(addrSpace AddressSpace, address net.IP) {
	if address == nil {
		return
	}
	ver := getAddressVersion(address)
	if ver == v4 {
		address = address.To4()
	}
	for _, subKey := range a.getSubnetList(addrSpace, ver) {
		a.Lock()
		space := a.addresses[subKey]
		a.Unlock()
		sub := subKey.canonicalChildSubnet()
		if sub.Contains(address) {
			// Retrieve correspondent ordinal in the subnet
			ordinal := ipToInt(getHostPortionIP(address, sub))
			// Release it
			for {
				var err error
				if err = space.PushReservation(ordinal/8, ordinal%8, true); err == nil {
					break
				}
				if _, ok := err.(types.RetryError); ok {
					// bitmask must have changed, retry delete
					continue
				}
				log.Warnf("Failed to release address %s because of internal error: %s", address.String(), err.Error())
				return
			}
			return
		}

	}
}
示例#10
0
文件: ip.go 项目: Cepave/lvs-metrics
// removeRoutes deletes the routing table entries for a VIP, from the specified
// table.
func removeRoutes(table string, vip net.IP) error {
	af := seesaw.IPv6
	if vip.To4() != nil {
		af = seesaw.IPv4
	}
	return ipRunAF(af, "route flush table %s %s", table, vip)
}
示例#11
0
func macAddress() (string, error) {
	ifaces, err := net.Interfaces()

	if err != nil {
		return "", err
	}

	for _, iface := range ifaces {
		if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
			// interface down or loopback interface
			continue
		}
		addrs, err := iface.Addrs()
		if err != nil {
			return "", err
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			if ip == nil || ip.IsLoopback() || ip.To4() == nil {
				continue
			}
			return iface.HardwareAddr.String(), nil
		}
	}
	return "", errors.New("not connected to the network")
}
示例#12
0
文件: main.go 项目: CNDonny/scope
func main() {
	defer util.Run()()
	router, err := routing.New()
	if err != nil {
		log.Fatal("routing error:", err)
	}
	for _, arg := range flag.Args() {
		var ip net.IP
		if ip = net.ParseIP(arg); ip == nil {
			log.Printf("non-ip target: %q", arg)
			continue
		} else if ip = ip.To4(); ip == nil {
			log.Printf("non-ipv4 target: %q", arg)
			continue
		}
		// Note:  newScanner creates and closes a pcap Handle once for
		// every scan target.  We could do much better, were this not an
		// example ;)
		s, err := newScanner(ip, router)
		if err != nil {
			log.Printf("unable to create scanner for %v: %v", ip, err)
			continue
		}
		if err := s.scan(); err != nil {
			log.Printf("unable to scan %v: %v", ip, err)
		}
		s.close()
	}
}
示例#13
0
// isMulticastAvailable returns true if ifi is a multicast access
// enabled network interface.  It also returns a unicast IPv4 address
// that can be used for listening on ifi.
func isMulticastAvailable(ifi *net.Interface) (net.IP, bool) {
	if ifi.Flags&net.FlagUp == 0 || ifi.Flags&net.FlagMulticast == 0 {
		return nil, false
	}
	ifat, err := ifi.Addrs()
	if err != nil {
		return nil, false
	}
	if len(ifat) == 0 {
		return nil, false
	}
	var ip net.IP
	for _, ifa := range ifat {
		switch v := ifa.(type) {
		case *net.IPAddr:
			ip = v.IP
		case *net.IPNet:
			ip = v.IP
		default:
			continue
		}
		if ip.To4() == nil {
			ip = nil
			continue
		}
		break
	}
	return ip, true
}
示例#14
0
文件: util.go 项目: rhino1998/cluster
func GetLocalIP() (ip net.IP, err error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	// handle err
	for _, i := range ifaces {
		addrs, err := i.Addrs()
		if err != nil {
			return nil, err
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP

			case *net.IPAddr:
				ip = v.IP
			}
			log.Println(ip.String())
			if !ip.IsLoopback() && ip.String() != "0.0.0.0" && ip.To4() != nil {
				return ip, nil
			}
		}
	}
	return nil, err
}
// Add a new default gateway. Identical to:
// ip route add default via $ip
func AddDefaultGw(ip net.IP) error {
	s, err := getNetlinkSocket()
	if err != nil {
		return err
	}
	defer s.Close()

	family := getIpFamily(ip)

	wb := newNetlinkRequest(syscall.RTM_NEWROUTE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)

	msg := newRtMsg(family)
	wb.AddData(msg)

	var ipData []byte
	if family == syscall.AF_INET {
		ipData = ip.To4()
	} else {
		ipData = ip.To16()
	}

	gateway := newRtAttr(syscall.RTA_GATEWAY, ipData)

	wb.AddData(gateway)

	if err := s.Send(wb); err != nil {
		return err
	}

	return s.HandleAck(wb.Seq)
}
示例#16
0
文件: iface.go 项目: JamesClonk/gohop
func setTunIP(iface *water.Interface, ip net.IP, subnet *net.IPNet) (err error) {
	ip = ip.To4()
	logger.Debug("%v", ip)
	if ip[3]%2 == 0 {
		return invalidAddr
	}

	peer := net.IP(make([]byte, 4))
	copy([]byte(peer), []byte(ip))
	peer[3]++
	tun_peer = peer

	sargs := fmt.Sprintf("addr add dev %s local %s peer %s", iface.Name(), ip, peer)
	args := strings.Split(sargs, " ")
	cmd := exec.Command("ip", args...)
	logger.Info("ip %s", sargs)
	err = cmd.Run()
	if err != nil {
		return err
	}

	sargs = fmt.Sprintf("route add %s via %s dev %s", subnet, peer, iface.Name())
	args = strings.Split(sargs, " ")
	cmd = exec.Command("ip", args...)
	logger.Info("ip %s", sargs)
	err = cmd.Run()
	return err
}
示例#17
0
func get_ips() ([]string, error) {
	ips := make([]string, 0)
	ifaces, err := net.Interfaces()
	if err != nil {
		log.Println(err)
		return ips, nil
	}
	for _, iface := range ifaces {
		// log.Println(iface.Name)
		addrs, err := iface.Addrs()
		if err != nil {
			return ips, nil
		}
		for _, addr := range addrs {
			// log.Println(addr.Network(), addr.String())
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			// 只保留ipv4地址
			if ip.To4() != nil && ip.String() != "127.0.0.1" {
				ips = append(ips, ip.String())
			}
		}
	}
	return ips, nil
}
示例#18
0
文件: address.go 项目: kat-co/juju
// IPv4ToDecimal converts a dotted quad IP address to its decimal equivalent.
func IPv4ToDecimal(ipv4Addr net.IP) (uint32, error) {
	ip := ipv4Addr.To4()
	if ip == nil {
		return 0, errors.Errorf("%q is not a valid IPv4 address", ipv4Addr.String())
	}
	return binary.BigEndian.Uint32([]byte(ip)), nil
}
示例#19
0
文件: util.go 项目: jchris/indexing
// GetLocalIP return the first external-IP4 configured for the first
// interface connected to this node.
func GetLocalIP() (net.IP, error) {
	interfaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	for _, iface := range interfaces {
		if (iface.Flags & net.FlagUp) == 0 {
			continue // interface down
		}
		if (iface.Flags & net.FlagLoopback) != 0 {
			continue // loopback interface
		}
		addrs, err := iface.Addrs()
		if err != nil {
			return nil, err
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			if ip != nil && !ip.IsLoopback() {
				if ip = ip.To4(); ip != nil {
					return ip, nil
				}
			}
		}
	}
	return nil, errors.New("cannot find local IP address")
}
示例#20
0
// print interfaces to know where the proxy is listening
func printInterfaces() {
	addrs, err := net.InterfaceAddrs()

	if err != nil {
		fmt.Println("Can't get interfaces. You have to have at least one network connection.")
		log.Fatal("No interface found")
	}

	for _, addr := range addrs {

		var ip net.IP
		switch v := addr.(type) {
		case *net.IPAddr:
		case *net.IPNet:
			ip = v.IP
		}

		if ip == nil || ip.IsLoopback() {
			continue
		}

		ip = ip.To4()
		if ip == nil {
			continue // not an ipv4 address
		}
		fmt.Println("http://" + ip.String() + Config.Service.Listen)
	}
}
func ipIsLocal(ip net.IP) bool {
	if ip.To4() == nil {
		return ip.Equal(net.IPv6loopback)
	}

	return v4Loopback.Contains(ip)
}
示例#22
0
// Lookup takes an IP address as a net.IP structure and a pointer to the
// result value to decode into. The result value pointed to must be a data
// value that corresponds to a record in the database. This may include a
// struct representation of the data, a map capable of holding the data or an
// empty interface{} value.
//
// If result is a pointer to a struct, the struct need not include a field
// for every value that may be in the database. If a field is not present in
// the structure, the decoder will not decode that field, reducing the time
// required to decode the record.
//
// Currently the decoder expect most data types to correspond exactly (e.g.,
// a uint64 database type must be decoded into a uint64 Go type). In the
// future, this may be made more flexible.
func (r *Reader) Lookup(ipAddress net.IP, result interface{}) error {
	if ipAddress == nil {
		return errors.New("ipAddress passed to Lookup cannot be nil")
	}

	ipV4Address := ipAddress.To4()
	if ipV4Address != nil {
		ipAddress = ipV4Address
	}
	if len(ipAddress) == 16 && r.Metadata.IPVersion == 4 {
		return fmt.Errorf("error looking up '%s': you attempted to look up an IPv6 address in an IPv4-only database", ipAddress.String())
	}

	pointer, err := r.findAddressInTree(ipAddress)

	if pointer == 0 {
		return err
	}

	rv := reflect.ValueOf(result)
	if rv.Kind() != reflect.Ptr || rv.IsNil() {
		return errors.New("result param for Lookup must be a pointer")
	}
	return r.resolveDataPointer(pointer, rv)
}
示例#23
0
// 一个接口上的所有ip4地址
func addrsOfOneInterface(iface net.Interface) (addrs []*net.IPAddr) {
	ifaddrs, err := iface.Addrs()

	if (err != nil) || (len(ifaddrs) == 0) {
		return
	}

	for _, ifaddr := range ifaddrs {
		var ip net.IP
		switch v := ifaddr.(type) {
		case *net.IPNet:
			ip = v.IP
		case *net.IPAddr:
			ip = v.IP
		default:
			continue
		}
		if ip.IsLoopback() {
			return
		}
		ip = ip.To4()
		if ip != nil {
			addr, _ := net.ResolveIPAddr("ip", ip.String())
			addrs = append(addrs, addr)
		}
	}
	return
}
示例#24
0
// newRequestPacket mimics the raw logic of RequestPacket, and verifies that
// its behavior does not change.
func newRequestPacket(mt MessageType, chAddr net.HardwareAddr, cIAddr net.IP, xId []byte, broadcast bool, options []Option) Packet {
	// Craft packet using our test method
	p := newPacket(BootRequest)

	// SetCHAddr
	copy(p[28:44], chAddr)
	p[2] = byte(len(chAddr))

	// SetXId
	copy(p[4:8], xId)

	// SetCIAddr
	if cIAddr != nil {
		copy(net.IP(p[12:16]), cIAddr.To4())
	}

	// SetBroadcast
	if broadcast {
		p[10:12][0] ^= 128
	}

	// AddOption already tested, so no need to duplicate the logic
	p.AddOption(OptionDHCPMessageType, []byte{byte(mt)})
	for _, o := range options {
		p.AddOption(o.Code, o.Value)
	}

	// PadToMinSize already tested
	p.PadToMinSize()

	return p
}
示例#25
0
func IpToRadixkey(prefix net.IP, prefixLen uint8) string {
	b := prefix.To4()
	if b == nil {
		b = prefix.To16()
	}
	return toRadixkey(b, prefixLen)
}
示例#26
0
func makeMac(ip net.IP) string {
	hw := make(net.HardwareAddr, 6)
	hw[0] = 0x7a
	hw[1] = 0x42
	copy(hw[2:], ip.To4())
	return hw.String()
}
示例#27
0
文件: agent.go 项目: nak3/nomad
// findLoopbackDevice iterates through all the interfaces on a machine and
// returns the ip addr, mask of the loopback device
func (a *Agent) findLoopbackDevice() (string, string, string, error) {
	var ifcs []net.Interface
	var err error
	ifcs, err = net.Interfaces()
	if err != nil {
		return "", "", "", err
	}
	for _, ifc := range ifcs {
		addrs, err := ifc.Addrs()
		if err != nil {
			return "", "", "", err
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			if ip.IsLoopback() {
				if ip.To4() == nil {
					continue
				}
				return ifc.Name, ip.String(), addr.String(), nil
			}
		}
	}

	return "", "", "", fmt.Errorf("no loopback devices with IPV4 addr found")
}
示例#28
0
文件: ip.go 项目: peer23peer/quasar
func LocalIP() (net.IP, error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	for _, i := range ifaces {
		addrs, err := i.Addrs()
		if err != nil {
			return nil, err
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			v4 := ip.To4()
			if v4 != nil && (v4[0] == 192 || v4[0] == 172 || v4[0] == 10) {
				return v4, nil
			}
		}
	}
	return nil, errors.New("cannot find local IP address")
}
示例#29
0
文件: tun.go 项目: blahgeek/justvpn
func (tun *_BaseTun) SetIPv4(typ int, ip net.IP) error {
	if typ == NETMASK {
		// Hack for OSX
		// must set IP Address again after setting netmask
		defer func() {
			ip, err := tun.GetIPv4(ADDRESS)
			if err == nil {
				tun.SetIPv4(ADDRESS, ip)
			}
		}()
	}
	ifreq := _IfReqIPv4{family: syscall.AF_INET}
	copy(ifreq.name[:], tun.name)
	if ipv4 := ip.To4(); ipv4 == nil {
		return fmt.Errorf("Invalid IPv4 Address %v", ip)
	} else {
		copy(ifreq.address[:], ipv4)
	}
	var cmd uintptr
	switch typ {
	case ADDRESS:
		cmd = syscall.SIOCSIFADDR
	case DST_ADDRESS:
		cmd = syscall.SIOCSIFDSTADDR
	case NETMASK:
		cmd = syscall.SIOCSIFNETMASK
	default:
		return fmt.Errorf("Invalid type %v", typ)
	}
	return ioctl(cmd, uintptr(unsafe.Pointer(&ifreq)))
}
示例#30
0
文件: session.go 项目: changlan/kytan
func NewSessionTable(addr net.IP) *SessionTable {
	return &SessionTable{
		binary.BigEndian.Uint32(addr.To4()),
		make(map[uint32]*net.UDPAddr),
		2,
	}
}