本文整理匯總了Golang中net.IPMask函數的典型用法代碼示例。如果您正苦於以下問題:Golang IPMask函數的具體用法?Golang IPMask怎麽用?Golang IPMask使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了IPMask函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: parseMask
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: TestGetHostOnlyNetworkWindows10Bug
// 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: cd_netmask
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: ReadIPList
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: getSubnet
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: teardownKvmNets
// 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)
}
}
}
示例7: main
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: resolvePeer
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: unmarshalIPMask
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: ReadIPList
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: NextAddr
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: maskToPrefixlen
// 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: setupNetworks
// 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: parseMask
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: GenerateNetworkInterfaceUnits
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
}