Exemplo n.º 1
0
func (i *Intface) getInt() error {
	if i.Interface != "" && i.iface == nil {
		ints, err := net.Interfaces()
		if err != nil {
			return e.New(err)
		}
		for _, in := range ints {
			if in.Name == i.Interface {
				i.iface = &in
				return nil
			}
		}
		return e.New("none interface with this name")
	} else if i.Interface == "" && i.iface == nil {
		ints, err := net.Interfaces()
		if err != nil {
			return e.New(err)
		}
		var intName string
		for _, in := range ints {
			if in.Flags&net.FlagMulticast == net.FlagMulticast || in.Flags&net.FlagBroadcast == net.FlagBroadcast || in.Flags&net.FlagBroadcast == net.FlagBroadcast {
				_, intName = getInterface(in)
				if intName == "" {
					continue
				}
				i.Interface = intName
				i.iface = &in
				break
			}
		}
	}
	return nil
}
Exemplo n.º 2
0
func TestHelper(t *testing.T) {
	g := Goblin(t)

	g.Describe(`PrivateInterface`, func() {
		g.Describe(`with a valid interface`, func() {
			g.It(`returns the correct interface`, func() {
				ifaces, _ := net.Interfaces()
				addrs, _ := ifaces[0].Addrs()
				localAddr := addrs[0]
				ip := localAddr.String()
				switch v := localAddr.(type) {
				case *net.IPAddr:
					ip = v.IP.String()
				case *net.IPNet:
					ip = v.IP.String()
				}
				ifaceName, err := PrivateInterface(ifaces, ip)
				g.Assert(ifaceName).Equal(ifaces[0].Name)
				g.Assert(err).Equal(nil)
			})
		})

		g.It(`with an invalid IP`, func() {
			ifaces, _ := net.Interfaces()
			ifaceName, err := PrivateInterface(ifaces, `somethingBad`)
			g.Assert(ifaceName).Equal(``)
			g.Assert(err).Equal(errors.New(`local interface could not be found`))
		})
	})

	g.Describe(`LocalAddress`, func() {
		g.Describe(`with a private interface`, func() {
			g.Describe(`with an ipv4 address`, func() {
				g.It(`returns the ip address`, func() {
					data := decodeMetadata(`{"interfaces": {"private": [{"ipv4": {"ip_address": "privateIP"}}]}}`)
					addr, _ := LocalAddress(data)
					g.Assert(addr).Equal(`privateIP`)
				})
			})

			g.Describe(`without an ipv4 address`, func() {
				g.It(`returns an error`, func() {
					data := decodeMetadata(`{"interfaces": {"public": [{"ipv4": {"ip_address": "publicIP"}}]}}`)
					_, err := LocalAddress(data)
					g.Assert(err).Equal(errors.New(`no private interfaces`))
				})
			})
		})

		g.Describe(`without a private interface`, func() {
			g.It(`returns an error`, func() {
				data := &metadata.Metadata{}
				_, err := LocalAddress(data)
				g.Assert(err).Equal(errors.New(`no private interfaces`))
			})
		})
	})
}
Exemplo n.º 3
0
func main() {
	flag.Parse()

	interfaces, err := net.Interfaces()
	if err == nil {
		for _, intf := range interfaces {
			addrs, err := intf.Addrs()
			if err != nil {
				continue
			}
			for _, a := range addrs {
				if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						if len(*uri) > 0 {
							httpHealthCheck(ipnet.IP.String())
						} else {
							portHealthCheck(ipnet.IP.String())
						}
					}
				}
			}
		}
	}

	fmt.Println("healthcheck failed")
	os.Exit(1)
}
Exemplo n.º 4
0
// New TUN device
func New() (Tun, error) {
	var tun Tun
	var name string
	ifaces, err := net.Interfaces()
	if err != nil {
		return tun, nil
	}

	for i := 0; ; i += 1 {
		name = "tun" + strconv.Itoa(i)
		iface_exist := false
		for _, iface := range ifaces {
			if strings.Contains(iface.Name, name) {
				iface_exist = true
			}
		}
		if !iface_exist {
			break
		}
	}

	log.WithField("name", name).Info("Allocating TUN interface")

	switch runtime.GOOS {
	case "darwin":
		tun = &UTun{}
	case "linux":
		tun = &LinuxTun{}
	default:
		return nil, fmt.Errorf("Tun not supported in %v", runtime.GOOS)
	}
	err = tun.Create(name)
	return tun, err
}
Exemplo n.º 5
0
Arquivo: mxio.go Projeto: ARolek/mxio
// init — we just want to make sure that the default values are good values.
// As the zero values don't make sense, this make the zero values acceptable values.
// If a network interface to use is not provided, we use the first device that is
// ip and able to Broadcast. If not devices are found we return an error of NoInterfaces.
func (m *Mxio) init() error {
	if m == nil {
		return errors.New("Mxio can not be nil!")
	}
	if m.DeviceType == DeviceType(0) {
		m.DeviceType = ALL_DEVICES
	}
	if m.IF == nil {
		interfaces, err := net.Interfaces()
		if len(interfaces) == 0 {
			return NoInterfaces
		}
		if err != nil {
			return err
		}
		for _, ifc := range interfaces {
			if (ifc.Flags & (net.FlagUp | net.FlagBroadcast)) != 0 {
				m.IF = &ifc
				break
			}
		}
		if m.IF == nil {
			return NoInterfaces
		}
	}
	if m.Timeout == 0 {
		// we want to default the timeout to 5 seconds
		m.Timeout = 5 * time.Second
	}
	if m.Retry == 0 {
		// we want the default the retry to 3
		m.Retry = 3
	}
	return nil
}
Exemplo n.º 6
0
func (m *Manager) uploadUsage() {
	id := "anon"
	ifaces, err := net.Interfaces()
	if err == nil {
		for _, iface := range ifaces {
			if iface.Name != "lo" {
				hw := iface.HardwareAddr.String()
				id = strings.Replace(hw, ":", "", -1)
				break
			}
		}
	}
	info := m.clusterManager.ClusterInfo()
	usage := &shipyard.Usage{
		ID:              id,
		Version:         m.version,
		NumOfEngines:    info.EngineCount,
		NumOfImages:     info.ImageCount,
		NumOfContainers: info.ContainerCount,
		TotalCpus:       info.Cpus,
		TotalMemory:     info.Memory,
	}
	b, err := json.Marshal(usage)
	if err != nil {
		logger.Warnf("error serializing usage info: %s", err)
	}
	buf := bytes.NewBuffer(b)
	if _, err := http.Post(fmt.Sprintf("%s/update", trackerHost), "application/json", buf); err != nil {
		logger.Warnf("error sending usage info: %s", err)
	}
}
Exemplo n.º 7
0
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"
}
Exemplo n.º 8
0
/*
 * Generate a list of names for which the certificate will be valid.
 * This will include the hostname and ip address
 */
func mynames() ([]string, error) {
	h, err := os.Hostname()
	if err != nil {
		return nil, err
	}

	ret := []string{h}

	ifs, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	for _, iface := range ifs {
		if IsLoopback(&iface) {
			continue
		}

		addrs, err := iface.Addrs()
		if err != nil {
			return nil, err
		}

		for _, addr := range addrs {
			ret = append(ret, addr.String())
		}
	}

	return ret, nil
}
Exemplo n.º 9
0
func GetIPs(ifaceWanted string, familyWanted int) ([]string, error) {
	ips := make([]string, 0)
	ifaces, err := net.Interfaces()
	if err != nil {
		return ips, err
	}
	for _, iface := range ifaces {
		if iface.Name != ifaceWanted {
			continue
		}

		addrs, _ := iface.Addrs()
		for _, addr := range addrs {
			addrString := addr.String()
			ip, _, err := net.ParseCIDR(addrString)
			if err != nil {
				return ips, err
			}

			if strings.Contains(addrString, ".") && familyWanted == netlink.FAMILY_V4 ||
				strings.Contains(addrString, ":") && familyWanted == netlink.FAMILY_V6 {
				ips = append(ips, ip.String())
			}
		}
	}
	return ips, err
}
Exemplo n.º 10
0
func (resolver *addressResolver) ResolveIP(host string) (net.IP, error) {
	if host == "localhost" || host == "127.0.0.1" {
		if resolver.local != nil {
			return resolver.local, nil
		}
		if !resolver.checked {
			resolver.checked = true
			devices, err := net.Interfaces()
			if err != nil {
				return nil, err
			}
			for _, dev := range devices {
				if (dev.Flags&net.FlagUp != 0) && (dev.Flags&net.FlagLoopback == 0) {
					addrs, err := dev.Addrs()
					if err != nil {
						continue
					}
					for i := range addrs {
						if ip, ok := addrs[i].(*net.IPNet); ok {
							log.Printf("Using %v for %s", ip, host)
							resolver.local = ip.IP
							return resolver.local, nil
						}
					}
				}
			}
		}
	}
	addr, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		return nil, err
	}
	return addr.IP, nil
}
Exemplo n.º 11
0
func chooseInterface() string {
	interfaces, err := net.Interfaces()
	if err != nil {
		log.Fatalf("net.Interfaces: %s", err)
	}
	for _, iface := range interfaces {
		// Skip loopback
		if iface.Name == "lo" {
			continue
		}
		addrs, err := iface.Addrs()
		// Skip if error getting addresses
		if err != nil {
			log.Println("Error get addresses for interfaces %s. %s", iface.Name, err)
			continue
		}

		if len(addrs) > 0 {
			// This one will do
			return iface.Name
		}
	}

	return ""
}
func (s *systemInterfaceAddrs) Get() ([]InterfaceAddress, error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return []InterfaceAddress{}, bosherr.WrapError(err, "Getting network interfaces")
	}

	interfaceAddrs := []InterfaceAddress{}

	for _, iface := range ifaces {
		addrs, err := iface.Addrs()
		if err != nil {
			return []InterfaceAddress{}, bosherr.WrapErrorf(err, "Getting addresses of interface '%s'", iface.Name)
		}

		for _, addr := range addrs {
			ip, _, err := net.ParseCIDR(addr.String())
			if err != nil {
				return []InterfaceAddress{}, bosherr.WrapErrorf(err, "Parsing addresses of interface '%s'", iface.Name)
			}

			if ipv4 := ip.To4(); ipv4 != nil {
				interfaceAddrs = append(interfaceAddrs, NewSimpleInterfaceAddress(iface.Name, ipv4.String()))
			}
		}

	}

	return interfaceAddrs, nil
}
Exemplo n.º 13
0
func (d *Discoverer) startLocalIPv6Multicasts(localMCAddr string) {
	intfs, err := net.Interfaces()
	if err != nil {
		if debug {
			l.Debugln("discover: interfaces:", err)
		}
		l.Infoln("Local discovery over IPv6 unavailable")
		return
	}

	v6Intfs := 0
	for _, intf := range intfs {
		// Interface flags seem to always be 0 on Windows
		if runtime.GOOS != "windows" && (intf.Flags&net.FlagUp == 0 || intf.Flags&net.FlagMulticast == 0) {
			continue
		}

		mb, err := beacon.NewMulticast(localMCAddr, intf.Name)
		if err != nil {
			if debug {
				l.Debugln("discover: Start local v6:", err)
			}
			continue
		}

		d.beacons = append(d.beacons, mb)
		go d.recvAnnouncements(mb)
		v6Intfs++
	}

	if v6Intfs == 0 {
		l.Infoln("Local discovery over IPv6 unavailable")
	}
}
Exemplo n.º 14
0
// GetLocalAddrList returns a list of local IP addresses
func GetLocalAddrList() ([]string, error) {
	var addrList []string
	// get the link list
	intfList, err := net.Interfaces()
	if err != nil {
		return addrList, err
	}

	log.Debugf("Got address list(%d): %+v", len(intfList), intfList)

	// Loop thru each interface and add its ip addr to list
	for _, intf := range intfList {
		if strings.HasPrefix(intf.Name, "docker") || strings.HasPrefix(intf.Name, "veth") ||
			strings.HasPrefix(intf.Name, "vport") || strings.HasPrefix(intf.Name, "lo") {
			continue
		}

		addrs, err := intf.Addrs()
		if err != nil {
			return addrList, err
		}

		for _, addr := range addrs {
			addrList = append(addrList, addr.String())
		}
	}

	return addrList, err
}
Exemplo n.º 15
0
func GetNonLoIfaceWithAddrs(ipFamily int) (iface net.Interface, addrs []string, err error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return iface, nil, err
	}

	for _, i := range ifaces {
		if i.Flags&net.FlagLoopback == 0 {
			addrs, err = GetIPs(i.Name, ipFamily)
			if err != nil {
				return iface, addrs, fmt.Errorf("Cannot get IP address for interface %v: %v", i.Name, err)
			}

			if len(addrs) == 0 {
				continue
			}
			iface = i

			ifaceNameLower := strings.ToLower(i.Name)
			// Don't use rkt's interfaces
			if strings.Contains(ifaceNameLower, "cni") ||
				strings.Contains(ifaceNameLower, "veth") {
				continue
			}
			break
		}
	}
	return iface, addrs, err
}
Exemplo n.º 16
0
// HasLocalMac returns the mac addresses that match an input MAC regex
func HasLocalMAC(macstr string) (found bool, elements []element, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("HasLocalMac() -> %v", e)
		}
	}()
	found = false
	re, err := regexp.Compile("(?i)" + macstr)
	if err != nil {
		panic(err)
	}
	ifaces, err := net.Interfaces()
	if err != nil {
		panic(err)
	}
	for _, iface := range ifaces {
		if re.MatchString(iface.HardwareAddr.String()) {
			found = true
			var el element
			el.LocalMACAddr = iface.HardwareAddr.String()
			elements = append(elements, el)
		}
		stats.Examined++
	}
	return
}
Exemplo n.º 17
0
Arquivo: util.go Projeto: jlisee/cbd
// Returns the ID of the current machine
func GetMachineID() (m MachineID, err error) {
	// First grab all the interfaces
	ifaces, err := net.Interfaces()

	if err != nil {
		return
	}

	if len(ifaces) == 0 {
		err = fmt.Errorf("No network interfaces found!")
		return
	}

	// Build up list of all mac addresses
	macs := make([]string, 0, len(ifaces))

	for _, iface := range ifaces {
		str := iface.HardwareAddr.String()
		if len(str) > 0 {
			macs = append(macs, str)
		}
	}

	// Sort then and pick the first one
	sort.Strings(macs)

	m = MachineID(macs[0])

	return
}
Exemplo n.º 18
0
func getHostIPs(interfaceName string) ([]net.Addr, error) {
	hostInterfaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	var iface net.Interface
	for _, hostInterface := range hostInterfaces {
		if hostInterface.Name == interfaceName {
			iface = hostInterface
			break
		}
	}

	addrs, err := iface.Addrs()
	if err != nil {
		return nil, err
	}

	if len(addrs) == 0 {
		return nil, errors.New("no ip addresses assigned to interface")
	}

	return addrs, nil
}
Exemplo n.º 19
0
func GetServerIP() string {
	ifaces, err := net.Interfaces()
	if err != nil {
		log.Panic("Can't acess the network interfaces.")
	}
	var ip net.IP
	for _, i := range ifaces {
		addrs, err := i.Addrs()
		if err != nil {
			log.Panic("Can't read the IP.")
		}
		for _, addr := range addrs {
			switch v := addr.(type) {
			case *net.IPNet:
				//log.Printf("Evaluating IPNet: %v\r\n", v.IP)
				if (v.IP.To4() != nil) && !v.IP.IsLinkLocalUnicast() && !v.IP.IsLoopback() && !v.IP.IsMulticast() {
					ip = v.IP
				}
			case *net.IPAddr:
				//log.Printf("Evaluating IPAddr: %v\r\n", v.IP)
				if (v.IP.To4() != nil) && !v.IP.IsLinkLocalUnicast() && !v.IP.IsLoopback() && !v.IP.IsMulticast() {
					ip = v.IP
				}
			}
		}
	}
	// process IP address
	return ip.String()
}
Exemplo n.º 20
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
}
Exemplo n.º 21
0
// GetAllInterfaces iterates over all available network interfaces and finds all
// available IP addresses on each interface and converts them to
// sockaddr.IPAddrs, and returning the result as an array of IfAddr.
func GetAllInterfaces() (IfAddrs, error) {
	ifs, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	ifAddrs := make(IfAddrs, 0, len(ifs))
	for _, intf := range ifs {
		addrs, err := intf.Addrs()
		if err != nil {
			return nil, err
		}

		for _, addr := range addrs {
			var ipAddr IPAddr
			ipAddr, err = NewIPAddr(addr.String())
			if err != nil {
				return IfAddrs{}, fmt.Errorf("unable to create an IP address from %q", addr.String())
			}

			ifAddr := IfAddr{
				SockAddr:  ipAddr,
				Interface: intf,
			}
			ifAddrs = append(ifAddrs, ifAddr)
		}
	}

	return ifAddrs, nil
}
Exemplo n.º 22
0
// GetIfacesByIP searches for and returns the interfaces with the given IP
// Disregards the subnet mask since not every net.IP object contains
// On success it will return the list of found interfaces
func (n *Networking) GetIfacesByIP(ifaceIP net.IP) ([]net.Interface, error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	searchAddr := strings.Split(ifaceIP.String(), "/")[0]
	resultInterfaces := make([]net.Interface, 0)

	for _, iface := range ifaces {
		if iface.Flags&net.FlagLoopback != 0 {
			continue
		}

		addrs, err := iface.Addrs()
		if err != nil {
			return nil, errwrap.Wrap(fmt.Errorf("cannot get addresses for interface %v", iface.Name), err)
		}

		for _, addr := range addrs {
			currentAddr := strings.Split(addr.String(), "/")[0]
			if searchAddr == currentAddr {
				resultInterfaces = append(resultInterfaces, iface)
				break
			}
		}
	}

	if len(resultInterfaces) == 0 {
		return nil, fmt.Errorf("no interface found with IP %q", ifaceIP)
	}

	return resultInterfaces, nil
}
Exemplo n.º 23
0
Arquivo: agent.go Projeto: 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")
}
Exemplo n.º 24
0
//
// 获取带有指定Prefix的Ip
//
func GetIpWithPrefix(prefix string) string {

	ifaces, _ := net.Interfaces()
	// handle err
	for _, i := range ifaces {
		addrs, _ := i.Addrs()
		// handle 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
			}

			ipAddr := ip.String()
			// fmt.Println("ipAddr: ", ipAddr)
			if strings.HasPrefix(ipAddr, prefix) {
				return ipAddr
			}

		}
	}
	return ""
}
Exemplo n.º 25
0
func main() {
	// 以下读取网卡信息
	Interface, err := net.Interfaces()
	if err != nil {
		panic("未发现网卡地址")
		os.Exit(1)
	}

	handwareAddrs = make(map[string]string, len(Interface))
	for _, inter := range Interface {
		inMAC := strings.ToUpper(inter.HardwareAddr.String())
		handwareAddrs[inMAC] = inMAC
	}

	if len(os.Args) != 2 {
		fmt.Println("为保障安全:请先绑定本机上的网卡地址")
		os.Exit(0)
	}

	addr := os.Args[1]
	h, e := net.ParseMAC(addr)
	if e != nil {
		fmt.Println("为保障安全:请先绑定本机上的网卡地址")
		fmt.Println("方法:client.exe 90-4C-E5-58-7E-FE")
		os.Exit(2)
	}
	inputMAC := strings.ToUpper(h.String())
	if inputMAC != handwareAddrs[inputMAC] {
		fmt.Println("网卡地址不匹配")
		os.Exit(0)
	}
}
Exemplo n.º 26
0
// 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")
}
Exemplo n.º 27
0
func (m DefaultManager) uploadUsage() {
	id := "anon"
	ifaces, err := net.Interfaces()
	if err == nil {
		for _, iface := range ifaces {
			if iface.Name != "lo" {
				hw := iface.HardwareAddr.String()
				id = strings.Replace(hw, ":", "", -1)
				break
			}
		}
	}
	usage := &shipyard.Usage{
		ID:      id,
		Version: version.Version,
	}
	b, err := json.Marshal(usage)
	if err != nil {
		log.Warnf("error serializing usage info: %s", err)
	}
	buf := bytes.NewBuffer(b)
	if _, err := http.Post(fmt.Sprintf("%s/update", trackerHost), "application/json", buf); err != nil {
		log.Warnf("error sending usage info: %s", err)
	}
}
Exemplo n.º 28
0
// nsenterIp displays the network interfaces inside a container's net namespace
func nsenterIp(config *libcontainer.Config, args []string) {
	interfaces, err := net.Interfaces()
	if err != nil {
		log.Fatal(err)
	}

	w := tabwriter.NewWriter(os.Stdout, 10, 1, 3, ' ', 0)
	fmt.Fprint(w, "NAME\tMTU\tMAC\tFLAG\tADDRS\n")

	for _, iface := range interfaces {
		addrs, err := iface.Addrs()
		if err != nil {
			log.Fatal(err)
		}

		o := []string{}

		for _, a := range addrs {
			o = append(o, a.String())
		}

		fmt.Fprintf(w, "%s\t%d\t%s\t%s\t%s\n", iface.Name, iface.MTU, iface.HardwareAddr, iface.Flags, strings.Join(o, ","))
	}

	w.Flush()
}
Exemplo n.º 29
0
func init() {
	if interfaces, err := net.Interfaces(); err == nil {
		for _, i := range interfaces {
			if i.Flags&net.FlagLoopback == 0 && len(i.HardwareAddr) > 0 {
				hardwareAddr = i.HardwareAddr
				break
			}
		}
	}
	if hardwareAddr == nil {
		// If we failed to obtain the MAC address of the current computer,
		// we will use a randomly generated 6 byte sequence instead and set
		// the multicast bit as recommended in RFC 4122.
		hardwareAddr = make([]byte, 6)
		_, err := io.ReadFull(rand.Reader, hardwareAddr)
		if err != nil {
			panic(err)
		}
		hardwareAddr[0] = hardwareAddr[0] | 0x01
	}

	// initialize the clock sequence with a random number
	var clockSeqRand [2]byte
	io.ReadFull(rand.Reader, clockSeqRand[:])
	clockSeq = uint32(clockSeqRand[1])<<8 | uint32(clockSeqRand[0])
}
Exemplo n.º 30
0
func getLocalIpAddress() string {
	interfaces, err := net.Interfaces()
	if err != nil {
		panic(err)
	}

	for _, netInterface := range interfaces {
		adresses, err := netInterface.Addrs()
		if err != nil {
			panic(err)
		}

		for _, address := range adresses {
			switch ipAddress := address.(type) {
			case *net.IPNet:
				ipString := fmt.Sprint(ipAddress.IP)
				if strings.HasPrefix(ipString, "127.") || ipString == "::1" {
					continue
				} else {
					return ipString
				}
			}
		}

	}

	return "127.0.0.1"
}