示例#1
0
文件: commands.go 项目: pzsz/sp0rkle
func parseMask(ips, nms string) string {
	ip := net.ParseIP(ips)
	nmip := net.ParseIP(nms)
	if ip == nil || nmip == nil {
		return fmt.Sprintf("either %s or %s couldn't be parsed as an IP",
			ips, nms)
	}
	// this is a bit of a hack, because using ParseIP to parse
	// something that's actually a v4 netmask doesn't quite work
	nm := net.IPMask(nmip.To4())
	cidr, bits := nm.Size()
	if ip.To4() != nil && nm != nil {
		if bits != 32 {
			return fmt.Sprintf("%s doesn't look like a valid IPv4 netmask", nms)
		}
	} else {
		// IPv6, hopefully
		nm = net.IPMask(nmip)
		cidr, bits = nm.Size()
		if bits != 128 {
			return fmt.Sprintf("%s doesn't look like a valid IPv6 netmask", nms)
		}
	}
	btm, top := maskRange(ip, nm)
	return fmt.Sprintf("%s/%d is in the range %s-%s and has the netmask %s",
		ip, cidr, btm, top, nmip)
}
示例#2
0
// Tests a special case where Virtualbox creates the host only network
// successfully but mis-reports the netmask.
func TestGetHostOnlyNetworkWindows10Bug(t *testing.T) {
	cidr := "192.168.99.0/24"
	ip, ipnet, err := net.ParseCIDR(cidr)
	if err != nil {
		t.Fatalf("Error parsing cidr: %s", err)
	}

	// This is a faulty netmask: a VirtualBox bug causes it to be
	// misreported.
	ipnet.Mask = net.IPMask(net.ParseIP("15.0.0.0").To4())

	expectedHostOnlyNetwork := &hostOnlyNetwork{
		IPv4: *ipnet,
	}

	vboxNets := map[string]*hostOnlyNetwork{
		"HostInterfaceNetworking-vboxnet0": expectedHostOnlyNetwork,
	}

	// The Mask that we are passing in will be the "legitimate" mask, so it
	// must differ from the magic buggy mask.
	n := getHostOnlyNetwork(vboxNets, ip, net.IPMask(net.ParseIP("255.255.255.0").To4()))
	if !reflect.DeepEqual(n, expectedHostOnlyNetwork) {
		t.Fatalf("Expected result of calling getHostOnlyNetwork to be the same as expected but it was not:\nexpected: %+v\nactual: %+v\n", expectedHostOnlyNetwork, n)
	}
}
示例#3
0
文件: handlers.go 项目: b33f/sp0rkle
func cd_netmask(bot *bot.Sp0rkle, line *base.Line, ips, nms string) {
	ip := net.ParseIP(ips)
	nmip := net.ParseIP(nms)
	if ip == nil || nmip == nil {
		bot.ReplyN(line, "either %s or %s couldn't be parsed as an IP", ips, nms)
		return
	}
	// this is a bit of a hack, because using ParseIP to parse
	// something that's actually a v4 netmask doesn't quite work
	nm := net.IPMask(nmip.To4())
	cidr, bits := nm.Size()
	if ip.To4() != nil && nm != nil {
		if bits != 32 {
			bot.ReplyN(line, "%s doesn't look like a valid IPv4 netmask", nms)
			return
		}
	} else {
		// IPv6, hopefully
		nm = net.IPMask(nmip)
		cidr, bits = nm.Size()
		if bits != 128 {
			bot.ReplyN(line, "%s doesn't look like a valid IPv6 netmask", nms)
			return
		}
	}
	btm, top := cd_netmask_range(ip, nm)
	bot.ReplyN(line, "%s/%d is in the range %s-%s and has the netmask %s",
		ip, cidr, btm, top, nmip)
}
示例#4
0
文件: iplist.go 项目: nicecai/goproxy
func ReadIPList(f io.Reader) (iplist IPList, err error) {
	reader := bufio.NewReader(f)

QUIT:
	for {
		line, err := reader.ReadString('\n')
		switch err {
		case io.EOF:
			if len(line) == 0 {
				break QUIT
			}
		case nil:
		default:
			logger.Err(err)
			return nil, err
		}
		addrs := strings.Split(strings.Trim(line, "\r\n "), " ")
		ipnet := net.IPNet{
			IP:   net.ParseIP(addrs[0]),
			Mask: net.IPMask(net.ParseIP(addrs[1])),
		}
		iplist = append(iplist, ipnet)
	}

	logger.Infof("blacklist loaded %d record(s).", len(iplist))
	return
}
示例#5
0
func getSubnet(ip, netmask string) (string, error) {
	// Check ip
	if net.ParseIP(ip) == nil {
		return "", fmt.Errorf("invalid IP address %s", ip)
	}

	// Check netmask
	maskIP := net.ParseIP(netmask).To4()
	if maskIP == nil {
		return "", fmt.Errorf("invalid Netmask %s", netmask)
	}

	// Get prefix
	mask := net.IPMask(maskIP)
	prefix, _ := mask.Size()

	// Get network
	sPrefix := strconv.Itoa(prefix)
	_, network, err := net.ParseCIDR(ip + "/" + sPrefix)
	if err != nil {
		return "", err
	}

	return network.IP.String() + "/" + sPrefix, nil
}
示例#6
0
文件: kvm.go 项目: vincentvdk/rkt
// teardownKvmNets teardown every active networking from networking by
// removing tuntap interface and releasing its ip from IPAM plugin
func (n *Networking) teardownKvmNets() {
	for _, an := range n.nets {
		switch an.conf.Type {
		case "ptp":
			// remove tuntap interface
			tuntap.RemovePersistentIface(an.runtime.IfName, tuntap.Tap)
			// remove masquerading if it was prepared
			if an.conf.IPMasq {
				h := sha512.Sum512([]byte(n.podID.String()))
				chain := fmt.Sprintf("CNI-%s-%x", an.conf.Name, h[:8])
				err := ip.TeardownIPMasq(&net.IPNet{
					IP:   an.runtime.IP,
					Mask: net.IPMask(an.runtime.Mask),
				}, chain)
				if err != nil {
					log.Printf("Error on removing masquerading: %q", err)
				}
			}
			// ugly hack again to directly call IPAM plugin to release IP
			an.conf.Type = an.conf.IPAM.Type

			_, err := n.execNetPlugin("DEL", &an, an.runtime.IfName)
			if err != nil {
				log.Printf("Error executing network plugin: %q", err)
			}
		default:
			log.Printf("Unsupported network type: %q", an.conf.Type)
		}
	}
}
func main() {
	flag.Parse()

	lwipv6.Initialize(0)
	defer lwipv6.Finish()

	intf := lwipv6.CreateInterface(lwipv6.IF_VDE, *socket, 0)
	if intf == nil {
		log.Fatalln("Interface setup failed to:", *socket)
	}

	ip := net.IPv4(192, 168, 123, 2)
	mask := net.IPMask(net.IPv4(255, 255, 255, 0))
	if intf.AddAddress(net.IPNet{ip, mask}) != 0 {
		log.Fatalln("Adding address failed.")
	}

	if intf.IfUp(0) != 0 {
		log.Fatalln("Failed bringing interface up")
	}

	fmt.Println("Interface up successfully! Press any key to exit.")
	var input string
	fmt.Scanln(&input)
	fmt.Println("Exiting.")
}
示例#8
0
func (d *driver) resolvePeer(nid string, peerIP net.IP) (net.HardwareAddr, net.IPMask, net.IP, error) {
	qPayload := fmt.Sprintf("%s %s", string(nid), peerIP.String())
	resp, err := d.serfInstance.Query("peerlookup", []byte(qPayload), nil)
	if err != nil {
		return nil, nil, nil, fmt.Errorf("resolving peer by querying the cluster failed: %v", err)
	}

	respCh := resp.ResponseCh()
	select {
	case r := <-respCh:
		var macStr, maskStr, vtepStr string
		if _, err := fmt.Sscan(string(r.Payload), &macStr, &maskStr, &vtepStr); err != nil {
			return nil, nil, nil, fmt.Errorf("bad response %q for the resolve query: %v", string(r.Payload), err)
		}

		mac, err := net.ParseMAC(macStr)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("failed to parse mac: %v", err)
		}

		return mac, net.IPMask(net.ParseIP(maskStr).To4()), net.ParseIP(vtepStr), nil

	case <-time.After(time.Second):
		return nil, nil, nil, fmt.Errorf("timed out resolving peer by querying the cluster")
	}
}
示例#9
0
func unmarshalIPMask(data []byte) (net.IPMask, error) {
	var bytes []byte
	if err := json.Unmarshal([]byte(data), &bytes); err != nil {
		return nil, err
	}
	return net.IPMask(bytes), nil
}
示例#10
0
func ReadIPList(filename string) (iplist IPList, err error) {
	var f io.ReadCloser
	f, err = os.Open(filename)
	if err != nil {
		return
	}
	defer f.Close()

	if strings.HasSuffix(filename, ".gz") {
		f, err = gzip.NewReader(f)
		if err != nil {
			return
		}
	}

	err = sutils.ReadLines(f, func(line string) (err error) {
		addrs := strings.Split(strings.Trim(line, "\r\n "), " ")
		ipnet := net.IPNet{IP: net.ParseIP(addrs[0]), Mask: net.IPMask(net.ParseIP(addrs[1]))}
		iplist = append(iplist, ipnet)
		return
	})
	if err != nil {
		return
	}
	return
}
示例#11
0
func (this pool) NextAddr(args ...interface{}) string {
	var addr, netmask string
	var ipnet *net.IPNet

	switch len(args) {
	case 2:
		addr = args[0].(string)
		netmask = args[1].(string)
		ipnet = &net.IPNet{
			IP:   net.ParseIP(addr),
			Mask: net.IPMask(net.ParseIP(netmask)),
		}

	case 0:
		for k, _ := range this.cache {
			ipnet = this.cache[k]
			break
		}
	default:
		return ""
	}

	ip, _, _ := net.ParseCIDR(this.NextCidr(ipnet.String()))

	return ip.String()
}
示例#12
0
文件: acl.go 项目: sysbot/goeapi
// maskToPrefixlen Converts a subnet mask from dotted decimal to bit length
// If mask is not in canonical form (i.e. ones followed by zeros) then
// returns 0
func maskToPrefixlen(mask string) string {
	if mask == "" {
		mask = "255.255.255.255"
	}
	prefixSize, _ := net.IPMask(net.ParseIP(mask).To4()).Size()
	return strconv.Itoa(prefixSize)
}
示例#13
0
文件: interfaces.go 项目: OSBI/juju
// setupNetworks prepares a []network.InterfaceInfo for the given instance. Any
// disabled network interfaces (as discovered from the lshw output for the node)
// will stay disabled.
func (environ *maasEnviron) setupNetworks(inst instance.Instance) ([]network.InterfaceInfo, error) {
	// Get the instance network interfaces first.
	interfaces, err := environ.getInstanceNetworkInterfaces(inst)
	if err != nil {
		return nil, errors.Annotatef(err, "getInstanceNetworkInterfaces failed")
	}
	logger.Debugf("node %q has network interfaces %v", inst.Id(), interfaces)
	networks, err := environ.getInstanceNetworks(inst)
	if err != nil {
		return nil, errors.Annotatef(err, "getInstanceNetworks failed")
	}
	logger.Debugf("node %q has networks %v", inst.Id(), networks)
	var tempInterfaceInfo []network.InterfaceInfo
	for _, netw := range networks {
		netCIDR := &net.IPNet{
			IP:   net.ParseIP(netw.IP),
			Mask: net.IPMask(net.ParseIP(netw.Mask)),
		}
		macs, err := environ.getNetworkMACs(netw.Name)
		if err != nil {
			return nil, errors.Annotatef(err, "getNetworkMACs failed")
		}
		logger.Debugf("network %q has MACs: %v", netw.Name, macs)
		var defaultGateway network.Address
		if netw.DefaultGateway != "" {
			defaultGateway = network.NewAddress(netw.DefaultGateway)
		}
		for _, mac := range macs {
			if ifinfo, ok := interfaces[mac]; ok {
				tempInterfaceInfo = append(tempInterfaceInfo, network.InterfaceInfo{
					MACAddress:     mac,
					InterfaceName:  ifinfo.InterfaceName,
					DeviceIndex:    ifinfo.DeviceIndex,
					CIDR:           netCIDR.String(),
					VLANTag:        netw.VLANTag,
					ProviderId:     network.Id(netw.Name),
					NetworkName:    netw.Name,
					Disabled:       ifinfo.Disabled,
					GatewayAddress: defaultGateway,
				})
			}
		}
	}
	// Verify we filled-in everything for all networks/interfaces
	// and drop incomplete records.
	var interfaceInfo []network.InterfaceInfo
	for _, info := range tempInterfaceInfo {
		if info.ProviderId == "" || info.NetworkName == "" || info.CIDR == "" {
			logger.Infof("ignoring interface %q: missing subnet info", info.InterfaceName)
			continue
		}
		if info.MACAddress == "" || info.InterfaceName == "" {
			logger.Infof("ignoring subnet %q: missing interface info", info.ProviderId)
			continue
		}
		interfaceInfo = append(interfaceInfo, info)
	}
	logger.Debugf("node %q network information: %#v", inst.Id(), interfaceInfo)
	return interfaceInfo, nil
}
示例#14
0
func parseMask(ips, nms string) string {
	ip := net.ParseIP(ips)
	nmip := net.ParseIP(nms)
	if ip == nil || nmip == nil {
		return fmt.Sprintf("either %s or %s couldn't be parsed as an IP",
			ips, nms)
	}
	if ip.To4() == nil && nmip.To4() != nil ||
		ip.To4() != nil && nmip.To4() == nil {
		return fmt.Sprintf("can't mix v4 and v6 ip / netmask specifications")
	}
	v4 := ip.To4() != nil
	if v4 {
		// Ensure we're working with 32-bit addrs.
		ip = ip.To4()
		nmip = nmip.To4()
	}
	// this is a bit of a hack, because using ParseIP to parse
	// something that's actually a v4 netmask doesn't quite work
	nm := net.IPMask(nmip)
	cidr, bits := nm.Size()
	if v4 && bits != 32 {
		return fmt.Sprintf("%s doesn't look like a valid IPv4 netmask", nms)
	} else if !v4 && bits != 128 {
		return fmt.Sprintf("%s doesn't look like a valid IPv6 netmask", nms)
	}
	btm, top := maskRange(ip, nm)
	if v4 {
		// Ditto.
		btm = btm.To4()
		top = top.To4()
	}
	return fmt.Sprintf("%s/%d is in the range %s-%s and has the netmask %s",
		ip, cidr, btm, top, nmip)
}
示例#15
0
文件: network.go 项目: matomesc/rkt
func GenerateNetworkInterfaceUnits(unitsPath string, netDescriptions []netDescriber) error {

	for i, netDescription := range netDescriptions {
		ifName := fmt.Sprintf(networking.IfNamePattern, i)
		netAddress := net.IPNet{
			IP:   netDescription.GuestIP(),
			Mask: net.IPMask(netDescription.Mask()),
		}

		address := netAddress.String()

		mac, err := generateMacAddress()
		if err != nil {
			return err
		}

		opts := []*unit.UnitOption{
			unit.NewUnitOption("Unit", "Description", fmt.Sprintf("Network configuration for device: %v", ifName)),
			unit.NewUnitOption("Unit", "DefaultDependencies", "false"),
			unit.NewUnitOption("Service", "Type", "oneshot"),
			unit.NewUnitOption("Service", "RemainAfterExit", "true"),
			unit.NewUnitOption("Service", "ExecStartPre", downInterfaceCommand(ifName)),
			unit.NewUnitOption("Service", "ExecStartPre", setMacCommand(ifName, mac.String())),
			unit.NewUnitOption("Service", "ExecStartPre", upInterfaceCommand(ifName)),
			unit.NewUnitOption("Service", "ExecStart", addAddressCommand(address, ifName)),
			unit.NewUnitOption("Install", "RequiredBy", "default.target"),
		}

		for _, route := range netDescription.Routes() {
			gw := route.GW
			if gw == nil {
				gw = netDescription.Gateway()
			}

			opts = append(
				opts,
				unit.NewUnitOption(
					"Service",
					"ExecStartPost",
					addRouteCommand(route.Dst.String(), gw.String()),
				),
			)
		}

		unitName := fmt.Sprintf("interface-%s", ifName) + ".service"
		unitBytes, err := ioutil.ReadAll(unit.Serialize(opts))
		if err != nil {
			return fmt.Errorf("failed to serialize network unit file to bytes %q: %v", unitName, err)
		}

		err = ioutil.WriteFile(filepath.Join(unitsPath, unitName), unitBytes, 0644)
		if err != nil {
			return fmt.Errorf("failed to create network unit file %q: %v", unitName, err)
		}

		log.Printf("network unit created: %q in %q (iface=%q, addr=%q)", unitName, unitsPath, ifName, address)
	}
	return nil
}
示例#16
0
func (p *PacSandbox) isInNet(ipStr string, ipRangeStr string, ipMaskStr string) (bool, error) {
	ipNet := &net.IPNet{
		IP:   net.ParseIP(ipRangeStr),
		Mask: net.IPMask(net.ParseIP(ipMaskStr)),
	}

	return ipNet.Contains(net.ParseIP(ipStr)), nil
}
示例#17
0
文件: options.go 项目: matomesc/rkt
func parseSubnetMask(opts dhcp4.Options) net.IPMask {
	mask, ok := opts[dhcp4.OptionSubnetMask]
	if !ok {
		return nil
	}

	return net.IPMask(mask)
}
示例#18
0
文件: net.go 项目: nlf/dlite
func getNetAddress() (string, error) {
	rawAddr, _ := getHostAddress()
	addr := net.ParseIP(rawAddr)

	rawMask, _ := getNetMask()
	mask := net.IPMask(net.ParseIP(rawMask).To4())

	return addr.Mask(mask).String(), nil
}
示例#19
0
func (t *Tun) GetNetmask() (mask net.IPMask, err error) {
	var c_addr *C.char
	c_name := C.CString(t.Name)
	defer C.free(unsafe.Pointer(c_name))
	if C.if_getaddr(C.SIOCGIFNETMASK, c_name, &c_addr) < 0 {
		err = fmt.Errorf("get netmask fail")
		return
	}
	return net.IPMask(net.ParseIP(C.GoString(c_addr))), nil
}
示例#20
0
func getNetMask() (net.IPMask, error) {
	out, err := exec.Command("defaults", "read", CONFIG_PLIST, NET_MASK_KEY).Output()
	if err != nil {
		return nil, err
	}
	mask := net.ParseIP(strings.TrimSpace(string(out)))
	if mask == nil {
		return nil, fmt.Errorf("Could not get the network mask for vmnet")
	}
	return net.IPMask(mask.To4()), nil
}
func parseIPv4Mask(s string) net.IPMask {
	ip := parseIPv4(s)
	if ip == nil {
		return nil
	}
	mask := net.IPMask(ip)
	if bits, size := mask.Size(); bits == 0 || size == 0 {
		return nil
	}
	return mask
}
示例#22
0
文件: kvm.go 项目: nhlfr/rkt
// teardownKvmNets teardown every active networking from networking by
// removing tuntap interface and releasing its ip from IPAM plugin
func (n *Networking) teardownKvmNets() {
	for _, an := range n.nets {
		if an.conf.Type == "flannel" {
			if err := kvmTransformFlannelNetwork(&an); err != nil {
				stderr.PrintE("error transforming flannel network", err)
				continue
			}
		}

		switch an.conf.Type {
		case "ptp", "bridge":
			// remove tuntap interface
			tuntap.RemovePersistentIface(an.runtime.IfName, tuntap.Tap)

		case "macvlan":
			link, err := netlink.LinkByName(an.runtime.IfName)
			if err != nil {
				stderr.PrintE(fmt.Sprintf("cannot find link `%v`", an.runtime.IfName), err)
				continue
			} else {
				err := netlink.LinkDel(link)
				if err != nil {
					stderr.PrintE(fmt.Sprintf("cannot remove link `%v`", an.runtime.IfName), err)
					continue
				}
			}

		default:
			stderr.Printf("unsupported network type: %q", an.conf.Type)
			continue
		}
		// ugly hack again to directly call IPAM plugin to release IP
		an.conf.Type = an.conf.IPAM.Type

		_, err := n.execNetPlugin("DEL", &an, an.runtime.IfName)
		if err != nil {
			stderr.PrintE("error executing network plugin", err)
		}
		// remove masquerading if it was prepared
		if an.conf.IPMasq {
			chain := cniutils.FormatChainName(an.conf.Name, n.podID.String())
			comment := cniutils.FormatChainName(an.conf.Name, n.podID.String())
			err := ip.TeardownIPMasq(&net.IPNet{
				IP:   an.runtime.IP,
				Mask: net.IPMask(an.runtime.Mask),
			}, chain, comment)
			if err != nil {
				stderr.PrintE("error on removing masquerading", err)
			}
		}
	}
}
示例#23
0
func (d *driver) processEvent(u serf.UserEvent) {
	logrus.Debugf("Received user event name:%s, payload:%s\n", u.Name,
		string(u.Payload))

	var dummy, action, vtepStr, nid, eid, ipStr, maskStr, macStr string
	if _, err := fmt.Sscan(u.Name, &dummy, &vtepStr, &nid, &eid); err != nil {
		fmt.Printf("Failed to scan name string: %v\n", err)
	}

	if _, err := fmt.Sscan(string(u.Payload), &action,
		&ipStr, &maskStr, &macStr); err != nil {
		fmt.Printf("Failed to scan value string: %v\n", err)
	}

	logrus.Debugf("Parsed data = %s/%s/%s/%s/%s/%s\n", nid, eid, vtepStr, ipStr, maskStr, macStr)

	mac, err := net.ParseMAC(macStr)
	if err != nil {
		logrus.Errorf("Failed to parse mac: %v\n", err)
	}

	if d.serfInstance.LocalMember().Addr.String() == vtepStr {
		return
	}

	switch action {
	case "join":
		if err := d.peerAdd(nid, eid, net.ParseIP(ipStr), net.IPMask(net.ParseIP(maskStr).To4()), mac,
			net.ParseIP(vtepStr), true); err != nil {
			logrus.Errorf("Peer add failed in the driver: %v\n", err)
		}
	case "leave":
		if err := d.peerDelete(nid, eid, net.ParseIP(ipStr), net.IPMask(net.ParseIP(maskStr).To4()), mac,
			net.ParseIP(vtepStr), true); err != nil {
			logrus.Errorf("Peer delete failed in the driver: %v\n", err)
		}
	}
}
示例#24
0
func (a *HostAgent) UnbindVirtualIP(virtualIP *pool.VirtualIP) error {
	glog.Infof("Removing: %v", virtualIP.IP)

	binaryNetmask := net.IPMask(net.ParseIP(virtualIP.Netmask).To4())
	cidr, _ := binaryNetmask.Size()

	//sudo ip addr del 192.168.0.10/24 dev eth0
	if err := exec.Command("ip", "addr", "del", virtualIP.IP+"/"+strconv.Itoa(cidr), "dev", virtualIP.BindInterface).Run(); err != nil {
		return fmt.Errorf("Problem with removing virtual interface %+v: %v", virtualIP, err)
	}

	glog.Infof("Removed virtual interface: %+v", virtualIP)
	return nil
}
示例#25
0
// isInNet returns true if the IP address of the host matches the specified IP
// address pattern.
// mask is the pattern informing which parts of the IP address to match against.
// 0 means ignore, 255 means match.
func gopacIsInNet(host, pattern, mask string) bool {
	if len(host) == 0 {
		return false
	}

	address, err := net.ResolveIPAddr("ip4", host)

	if err != nil {
		return false
	}

	maskIp := net.IPMask(net.ParseIP(mask))
	return address.IP.Mask(maskIp).String() == pattern
}
示例#26
0
func (i *siNetIFInfo) UnmarshalJSON(data []byte) (err error) {
	var tmp struct {
		Metric      int    `json:"metric"`
		MTU         int    `json:"mtu"`
		Flags       int    `json:"flags"`
		Type        string `json:"type"`
		Name        string `json:"name"`
		Broadcast   string `json:"broadcast"`
		Address     string `json:"address"`
		Address6    string `json:"address6"`
		HWAddr      string `json:"hwaddr"`
		Destination string `json:"destination"`
		Netmask     string `json:"netmask"`
	}
	err = json.Unmarshal(data, &tmp)
	if err != nil {
		return
	}

	i.Metric = tmp.Metric
	i.MTU = tmp.MTU
	i.Flags = tmp.Flags
	i.Type = tmp.Type
	i.Name = tmp.Name

	i.Broadcast, err = net.ResolveIPAddr("ip", tmp.Broadcast)
	if err != nil {
		return
	}
	i.Address, err = net.ResolveIPAddr("ip", tmp.Address)
	if err != nil {
		return
	}
	i.Address6, err = net.ResolveIPAddr("ip", tmp.Address6)
	if err != nil {
		return
	}
	i.HWAddr, err = net.ParseMAC(tmp.HWAddr)
	if err != nil {
		return
	}
	i.Destination, err = net.ResolveIPAddr("ip", tmp.Destination)
	if err != nil {
		return
	}
	i.Netmask = net.IPMask(net.ParseIP(tmp.Netmask))
	return
}
示例#27
0
文件: util.go 项目: vjudge1/MEOW
// NetNbitIPv4Mask returns a IPMask with highest n bit set.
func NewNbitIPv4Mask(n int) net.IPMask {
	if n > 32 {
		panic("NewNbitIPv4Mask: bit number > 32")
	}
	mask := []byte{0, 0, 0, 0}
	for id := 0; id < 4; id++ {
		if n >= 8 {
			mask[id] = 0xff
		} else {
			mask[id] = ^byte(1<<(uint8(8-n)) - 1)
			break
		}
		n -= 8
	}
	return net.IPMask(mask)
}
示例#28
0
func parseIPv4Address(address Address) (net.IPNet, error) {
	ip := net.ParseIP(address.IPAddress)
	if ip == nil {
		return net.IPNet{}, fmt.Errorf("could not parse %q as IPv4 address", address.IPAddress)
	}

	mask := net.ParseIP(address.Netmask)
	if mask == nil {
		return net.IPNet{}, fmt.Errorf("could not parse %q as IPv4 mask", address.Netmask)
	}

	return net.IPNet{
		IP:   ip,
		Mask: net.IPMask(mask.To4()),
	}, nil
}
示例#29
0
// Convert a CIDR from hex representation to text, opposite of the above.
func asciiCIDR(cidr string) (string, error) {
	parts := strings.Split(cidr, "/")
	if len(parts) != 2 {
		return "", fmt.Errorf("unexpected CIDR format: %s", cidr)
	}
	ipData, err := hex.DecodeString(parts[0])
	if err != nil {
		return "", err
	}
	ip := net.IP(ipData)

	maskData, err := hex.DecodeString(parts[1])
	mask := net.IPMask(maskData)
	size, _ := mask.Size()

	return fmt.Sprintf("%s/%d", ip.String(), size), nil
}
示例#30
0
文件: impl.go 项目: keep94/Dominator
func findInterfaceForHost(hostname string) (string, error) {
	var hostIP net.IP
	if hostname == "" {
		hostIP = make(net.IP, 4)
	} else {
		hostIPs, err := net.LookupIP(hostname)
		if err != err {
			return "", err
		}
		if len(hostIPs) < 1 {
			return "", errors.New("not enough IPs")
		}
		hostIP = hostIPs[0]
	}
	file, err := os.Open(procRouteFilename)
	if err != nil {
		return "", err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	mostSpecificInterfaceName := ""
	mostSpecificNetmaskBits := -1
	for scanner.Scan() {
		var interfaceName string
		var destAddr, gatewayAddr, flags, mask uint32
		var ign int
		nCopied, err := fmt.Sscanf(scanner.Text(),
			"%s %x %x %x %d %d %d %x %d %d %d",
			&interfaceName, &destAddr, &gatewayAddr, &flags, &ign, &ign, &ign,
			&mask, &ign, &ign, &ign)
		if err != nil || nCopied < 11 {
			continue
		}
		maskIP := net.IPMask(intToIP(mask))
		destIP := intToIP(destAddr)
		if hostIP.Mask(maskIP).Equal(destIP) {
			size, _ := maskIP.Size()
			if size > mostSpecificNetmaskBits {
				mostSpecificInterfaceName = interfaceName
				mostSpecificNetmaskBits = size
			}
		}
	}
	return mostSpecificInterfaceName, scanner.Err()
}