Allocates an IP from the specified subnet and creates a port
513616
def allocate_ip_for_subnet(self, subnet_id, mac, port_id):
        """"""
        # Get an available IP and mark it as used before someone else does
        # If there's no IP, , log it and return an error
        # If we successfully get an IP, create a port with the specified MAC and device data
        # If port creation fails, deallocate the IP
        subnet = self.get_subnet(subnet_id)
        ip, mask, port_id = self.a10_allocate_ip_from_dhcp_range(subnet, "vlan", mac, port_id)
        return ip, mask, port_id
199943
def cli(env, identifier, no_vs, no_hardware):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)
    subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,
                                   name='subnet')
    subnet = mgr.get_subnet(subnet_id)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', subnet['id']])
    table.add_row(['identifier',
                   '%s/%s' % (subnet['networkIdentifier'],
                              str(subnet['cidr']))])
    table.add_row(['subnet type', subnet['subnetType']])
    table.add_row(['network space',
                   utils.lookup(subnet, 'networkVlan', 'networkSpace')])
    table.add_row(['gateway', subnet.get('gateway', formatting.blank())])
    table.add_row(['broadcast',
                   subnet.get('broadcastAddress', formatting.blank())])
    table.add_row(['datacenter', subnet['datacenter']['name']])
    table.add_row(['usable ips',
                   subnet.get('usableIpAddressCount', formatting.blank())])

    if not no_vs:
        if subnet['virtualGuests']:
            vs_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for vsi in subnet['virtualGuests']:
                vs_table.add_row([vsi['hostname'],
                                  vsi['domain'],
                                  vsi.get('primaryIpAddress'),
                                  vsi.get('primaryBackendIpAddress')])
            table.add_row(['vs', vs_table])
        else:
            table.add_row(['vs', 'none'])

    if not no_hardware:
        if subnet['hardware']:
            hw_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for hardware in subnet['hardware']:
                hw_table.add_row([hardware['hostname'],
                                  hardware['domain'],
                                  hardware.get('primaryIpAddress'),
                                  hardware.get('primaryBackendIpAddress')])
            table.add_row(['hardware', hw_table])
        else:
            table.add_row(['hardware', 'none'])

    env.fout(table)
296262
function(ip, options) {
    var self = this;
    this.ip = ip;
    this.openFlag = false;
    this.callback = null;

    // options
    if (typeof options === "undefined") options = {};
    this.port = options.port || TELNET_PORT; // telnet server port

    // internal buffer
    this._buffer = Buffer.alloc(0);
    this._id = 0;
    this._cmd = 0;
    this._length = 0;

    // handle callback - call a callback function only once, for the first event
    // it will triger
    var handleCallback = function(had_error) {
        if (self.callback) {
            self.callback(had_error);
            self.callback = null;
        }
    };

    // create a socket
    this._client = new net.Socket();
    if (options.timeout) this._client.setTimeout(options.timeout);

    // register the port data event
    this._client.on("data", function onData(data) {
        // add data to buffer
        self._buffer = Buffer.concat([self._buffer, data]);

        // check if buffer include a complete modbus answer
        var expectedLength = self._length;
        var bufferLength = self._buffer.length;
        modbusSerialDebug(
            "on data expected length:" +
                expectedLength +
                " buffer length:" +
                bufferLength
        );

        modbusSerialDebug({
            action: "receive tcp telnet port",
            data: data,
            buffer: self._buffer
        });
        modbusSerialDebug(
            JSON.stringify({
                action: "receive tcp telnet port strings",
                data: data,
                buffer: self._buffer
            })
        );

        // check data length
        if (expectedLength < 6 || bufferLength < EXCEPTION_LENGTH) return;

        // loop and check length-sized buffer chunks
        var maxOffset = bufferLength - EXCEPTION_LENGTH;
        for (var i = 0; i <= maxOffset; i++) {
            var unitId = self._buffer[i];
            var functionCode = self._buffer[i + 1];

            if (unitId !== self._id) continue;

            if (
                functionCode === self._cmd &&
                i + expectedLength <= bufferLength
            ) {
                self._emitData(i, expectedLength);
                return;
            }
            if (
                functionCode === (0x80 | self._cmd) &&
                i + EXCEPTION_LENGTH <= bufferLength
            ) {
                self._emitData(i, EXCEPTION_LENGTH);
                return;
            }

            // frame header matches, but still missing bytes pending
            if (functionCode === (0x7f & self._cmd)) break;
        }
    });

    this._client.on("connect", function() {
        self.openFlag = true;
        handleCallback();
    });

    this._client.on("close", function(had_error) {
        self.openFlag = false;
        handleCallback(had_error);
    });

    this._client.on("error", function(had_error) {
        self.openFlag = false;
        handleCallback(had_error);
    });

    this._client.on("timeout", function() {
        self.openFlag = false;
        modbusSerialDebug("TelnetPort port: TimedOut");
        handleCallback(new Error("TelnetPort Connection Timed Out."));
    });

    /**
     * Check if port is open.
     *
     * @returns {boolean}
     */
    Object.defineProperty(this, "isOpen", {
        enumerable: true,
        get: function() {
            return this.openFlag;
        }
    });

    EventEmitter.call(this);
}
1143727
def setup_xray_client(self, ip, port, client):
        
        if not client:
            client = self._create_xray_client(ip, port)
        self._xray_client = client
381778
function(x, y) {
  var ip,
    bits,
    arr,
    ip4,
    ip6;
  if (y === undefined) { // handed a string
    arr = x.split('/');
    this.subnet = arr[1];
    ip = arr[0];
  } else {
    this.subnet = y;
    ip = x;
  }


  ip4 = (ip instanceof Address4 ? ip : new Address4(ip));
  ip6 = (ip instanceof Address6 ? ip : new Address6(ip));

  this.v = (ip4.valid ? 4 : (ip6.valid ? 6 : 0));

  if (this.v === 6) {
    bits = 128;
  } else {
    bits = 32;
  }
  ip = makeAddr(ip, this.v);

  this.mask = generateCidrMask(bits, bits - this.subnet - 1);
  this.prefix = generatePrefix(ip, this.mask);
}
796604
def split_host_and_port(netloc: str) -> Tuple[str, Optional[int]]:
    
    match = re.match(r"^(.+):(\d+)$", netloc)
    if match:
        host = match.group(1)
        port = int(match.group(2))  # type: Optional[int]
    else:
        host = netloc
        port = None
    return (host, port)
1309272
function(ip) {
    this.connectionparams = {
        host: ip,
        port: 23,
        timeout: 1000, //  The RESPONSE should be sent within 200ms of receiving the request COMMAND. (plus network delay)
        sendTimeout: 1200,
        negotiationMandatory: false,
        ors: '\r', // Set outbound record separator
        irs: '\r'
    };
    this.cmdCue = [];
    this.connection = null;
}
741974
def allocate_port():
    
    sock = socket.socket()
    try:
        sock.bind(("localhost", 0))
        return get_port(sock)
    finally:
        sock.close()
451162
def create_payload(self):
        
        payload = super(Subnet, self).create_payload()
        if 'from_' in payload:
            payload['from'] = payload.pop('from_')
        return {u'subnet': payload}
963641
def configure_network(ip, netmask, gateway):
    '''
    
    '''
    current = network()

    # Check to see if the network is already configured
    if (ip in current['Network Settings']['IP_ADDRESS']['VALUE'] and
            netmask in current['Network Settings']['SUBNET_MASK']['VALUE'] and
            gateway in current['Network Settings']['GATEWAY_IP_ADDRESS']['VALUE']):
        return True

    _xml = """<RIBCL VERSION="2.0">
                <LOGIN USER_LOGIN="adminname" PASSWORD="password">
                  <RIB_INFO MODE="write">
                    <MOD_NETWORK_SETTINGS>
                      <IP_ADDRESS value="{0}"/>
                      <SUBNET_MASK value="{1}"/>
                      <GATEWAY_IP_ADDRESS value="{2}"/>
                    </MOD_NETWORK_SETTINGS>
                  </RIB_INFO>
                </LOGIN>
              </RIBCL> """.format(ip, netmask, gateway)

    return __execute_cmd('Configure_Network', _xml)
852262
public function ipCalculator($ip, $network_size)
    {
        try {
            $result = new SubnetCalculator($ip, $network_size);

            return $result->getSubnetArrayReport();
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();

            return $message;
        }
    }
653580
def setup(addr, user, remote_path, local_key=None):
    """"""
    port = find_port(addr, user)

    if not port or not is_alive(addr, user):
        port = new_port()

        scp(addr, user, __file__, '~/unixpipe', local_key)

        ssh_call = ['ssh', '-fL%d:127.0.0.1:12042' % port,
                    '-o', 'ExitOnForwardFailure=yes',
                    '-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' % port,
                    '-o', 'ControlMaster=auto',
                    '%s@%s' % (user, addr,), 'python', '~/unixpipe',
                    'server', remote_path]
        if local_key:
            ssh_call.insert(1, local_key)
            ssh_call.insert(1, '-i')

        subprocess.call(ssh_call)
        # XXX Sleep is a bad way to wait for the tunnel endpoint
        time.sleep(1)

    return port
1336609
def _create_hidden_port(self, context, network_id, device_id, fixed_ips,
                            port_type=DEVICE_OWNER_ROUTER_INTF):
        """"""
        port = {'port': {
            'tenant_id': '',  # intentionally not set
            'network_id': network_id,
            'mac_address': ATTR_NOT_SPECIFIED,
            'fixed_ips': fixed_ips,
            'device_id': device_id,
            'device_owner': port_type,
            'admin_state_up': True,
            'name': ''}}
        if extensions.is_extension_supported(self._core_plugin,
                                             "dns-integration"):
                port['port'].update(dns_name='')
        core_plugin = bc.get_plugin()
        return core_plugin.create_port(context, port)
955697
def _send(self, ip, port, data):
        
        return self._listen_socket.sendto(data, (ip, port))
996011
def create_ip_arp_reply(srchw, dsthw, srcip, targetip):
    '''
    
    '''
    pkt = create_ip_arp_request(srchw, srcip, targetip)
    pkt[0].dst = dsthw
    pkt[1].operation = ArpOperation.Reply
    pkt[1].targethwaddr = dsthw
    return pkt
1326438
def _addPort(n: LNode, lp: LPort, intf: Interface,
             reverseDirection=False):
    
    origin = originObjOfPort(intf)
    d = intf._direction
    d = PortTypeFromDir(d)

    if reverseDirection:
        d = PortType.opposite(d)

    new_lp = LPort(lp, d, lp.side, name=intf._name)
    new_lp.originObj = origin
    if intf._interfaces:
        for child_intf in intf._interfaces:
            _addPort(n, new_lp, child_intf,
                     reverseDirection=reverseDirection)

    lp.children.append(new_lp)
    new_lp.parent = lp
    if n._node2lnode is not None:
        n._node2lnode[origin] = new_lp

    return new_lp
60738
def inet_ntop(af, addr):
    """"""
    if af == socket.AF_INET:
        return inet_ntoa(addr)
    elif af == socket.AF_INET6:
        # IPv6 addresses have 128bits (16 bytes)
        if len(addr) != 16:
            raise Exception("Illegal syntax for IP address")
        parts = []
        for left in [0, 2, 4, 6, 8, 10, 12, 14]:
            try: 
                value = struct.unpack("!H", addr[left:left+2])[0]
                hexstr = hex(value)[2:]
            except TypeError:
                raise Exception("Illegal syntax for IP address")
            parts.append(hexstr.lstrip("0").lower())
        result = b":".join(parts)
        while b":::" in result:
            result = result.replace(b":::", b"::")
        # Leaving out leading and trailing zeros is only allowed with ::
        if result.endswith(b":") and not result.endswith(b"::"):
            result = result + b"0"
        if result.startswith(b":") and not result.startswith(b"::"):
            result = b"0" + result
        return result
    else:
        raise Exception("Address family not supported yet")