Set the IP address on a virtual interface (vif)
422266
def set_vm_ip(name=None,
              ipv4_cidr=None,
              ipv4_gw=None,
              session=None,
              call=None):
    '''
    

    '''
    mode = 'static'
    # TODO: Need to add support for IPv6
    if call == 'function':
        raise SaltCloudException(
            'The function must be called with -a or --action.')

    log.debug(
        'Setting name: %s ipv4_cidr: %s ipv4_gw: %s mode: %s',
        name, ipv4_cidr, ipv4_gw, mode
    )
    if session is None:
        log.debug('New session being created')
        session = _get_session()
    vm = _get_vm(name, session)
    # -- try to get ip from vif
    # TODO: for now will take first interface
    #       addition consideration needed for
    #       multiple interface(vif) VMs
    vifs = session.xenapi.VM.get_VIFs(vm)
    if vifs is not None:
        log.debug('There are %s vifs.', len(vifs))
        for vif in vifs:
            record = session.xenapi.VIF.get_record(vif)
            log.debug(record)
            try:
                session.xenapi.VIF.configure_ipv4(
                    vif, mode, ipv4_cidr, ipv4_gw)
            except XenAPI.Failure:
                log.info('Static IP assignment could not be performed.')

    return True
586462
def ip_host(value, options=None, version=None):
    '''
    
    '''
    ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
    if not ipaddr_filter_out:
        return
    if not isinstance(value, (list, tuple, types.GeneratorType)):
        return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0]))
    return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out]
830726
def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'):
    '''
    
    '''
    ret = set()

    ifaces = interface_data \
        if isinstance(interface_data, dict) \
        else interfaces()
    if interface is None:
        target_ifaces = ifaces
    else:
        target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces)
                              if k == interface])
        if not target_ifaces:
            log.error('Interface %s not found.', interface)
    for ip_info in six.itervalues(target_ifaces):
        addrs = ip_info.get(proto, [])
        addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto])

        for addr in addrs:
            addr = ipaddress.ip_address(addr.get('address'))
            if not addr.is_loopback or include_loopback:
                ret.add(addr)
    return [six.text_type(addr) for addr in sorted(ret)]
526700
def set_port_info(self, webport, mediaport, httpsport,
                                      onvifport, callback=None):
        '''
        
        '''
        params = {'webPort'   : webport,
                  'mediaPort' : mediaport,
                  'httpsPort' : httpsport,
                  'onvifPort' : onvifport,
                 }
        return self.execute_command('setPortInfo', params, callback=callback)
668167
def set_ip_info(self, is_dhcp, ip='', gate='', mask='',
                                dns1='', dns2='', callback=None):
        '''
        
        '''
        params = {'isDHCP': is_dhcp,
                  'ip': ip,
                  'gate': gate,
                  'mask': mask,
                  'dns1': dns1,
                  'dns2': dns2,
                 }

        return self.execute_command('setIpInfo', params, callback=callback)
687682
def pack_ip_addr(addr):
    """"""
    addr, port = addr
    return socket.inet_aton(addr) + struct.pack('!H', port & _short_mask)
560739
def set_ipv4(self, ip):
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        bin_ip = socket.inet_aton(ip)
        ifreq = struct.pack('16sH2s4s8s', self.name, socket.AF_INET, '\x00'*2, bin_ip, '\x00'*8)
        fcntl.ioctl(sock, self.SIOCSIFADDR, ifreq)
        ifreq = struct.pack('16sH', self.name, self.IFF_UP|self.IFF_POINTOPOINT|self.IFF_RUNNING|self.IFF_MULTICAST)
        fcntl.ioctl(sock, self.SIOCSIFFLAGS, ifreq)
831811
def create_api_v4_virtual_interface(self):
        """"""
        return ApiV4VirtualInterface(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
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")
979802
def _set_address(self, address, force=None):
        
        force = force if force is not None else self.force
        if self.address != address or self._force_last != force:
            if force is True:
                ioctl(self.fd, I2C_SLAVE_FORCE, address)
            else:
                ioctl(self.fd, I2C_SLAVE, address)
            self.address = address
            self._force_last = force
1245433
def ignore_cidr(vm_, ip):
    '''
    
    '''
    if HAS_NETADDR is False:
        log.error('Error: netaddr is not installed')
        return 'Error: netaddr is not installed'

    cidr = config.get_cloud_config_value(
        'ignore_cidr', vm_, __opts__, default='', search_global=False
    )
    if cidr != '' and all_matching_cidrs(ip, [cidr]):
        log.warning('IP "%s" found within "%s"; ignoring it.', ip, cidr)
        return True

    return False
1313454
def add_nic(self, instance_id, net_id):
        """"""
        #TODO: upgrade with port_id and fixed_ip in future
        self.client.servers.interface_attach(
            instance_id, None, net_id, None)
        return True
885603
def _set_virtualbox(self):
        
        '''
            
        '''

        from os import environ
        if not environ.get('DOCKER_CERT_PATH'):
            import re
            sys_command = 'docker-machine env %s' % self.vbox
            cmd_output = self.command(sys_command)
            variable_list = ['DOCKER_TLS_VERIFY', 'DOCKER_HOST', 'DOCKER_CERT_PATH', 'DOCKER_MACHINE_NAME']
            for variable in variable_list:
                env_start = '%s="' % variable
                env_end = '"\\n'
                env_regex = '%s.*?%s' % (env_start, env_end)
                env_pattern = re.compile(env_regex)
                env_statement = env_pattern.findall(cmd_output)
                env_var = env_statement[0].replace(env_start, '').replace('"\n', '')
                environ[variable] = env_var

        return True
140600
def enable_ipfix(bridge, target):
    '''
    '''
    cmd = ['ovs-vsctl', 'set', 'Bridge', bridge, 'ipfix=@i', '--',
           '--id=@i', 'create', 'IPFIX', 'targets="{}"'.format(target)]
    log('Enabling IPfix on {}.'.format(bridge))
    subprocess.check_call(cmd)
316847
def AddForwardedIp(self, address, interface):
    
    address = address if IP_ALIAS_REGEX.match(address) else '%s/32' % address
    args = ['add', 'to', 'local', address]
    options = self._CreateRouteOptions(dev=interface)
    self._RunIpRoute(args=args, options=options)
989727
def attach_ip(self, server, family='IPv4'):
        
        body = {
            'ip_address': {
                'server': str(server),
                'family': family
            }
        }

        res = self.request('POST', '/ip_address', body)
        return IPAddress(cloud_manager=self, **res['ip_address'])
963277
private VirtualMachine listenTarget(int port, List<String> remoteVMOptions) {
        ListeningConnector listener = (ListeningConnector) connector;
        // Files to collection to output of a start-up failure
        File crashErrorFile = createTempFile("error");
        File crashOutputFile = createTempFile("output");
        try {
            // Start listening, get the JDI connection address
            String addr = listener.startListening(connectorArgs);
            debug("Listening at address: " + addr);

            // Launch the RemoteAgent requesting a connection on that address
            String javaHome = System.getProperty("java.home");
            List<String> args = new ArrayList<>();
            args.add(javaHome == null
                    ? "java"
                    : javaHome + File.separator + "bin" + File.separator + "java");
            args.add("-agentlib:jdwp=transport=" + connector.transport().name() +
                    ",address=" + addr);
            args.addAll(remoteVMOptions);
            args.add(remoteAgent);
            args.add("" + port);
            ProcessBuilder pb = new ProcessBuilder(args);
            pb.redirectError(crashErrorFile);
            pb.redirectOutput(crashOutputFile);
            process = pb.start();

            // Accept the connection from the remote agent
            vm = timedVirtualMachineCreation(() -> listener.accept(connectorArgs),
                    () -> process.waitFor());
            try {
                listener.stopListening(connectorArgs);
            } catch (IOException | IllegalConnectorArgumentsException ex) {
                // ignore
            }
            crashErrorFile.delete();
            crashOutputFile.delete();
            return vm;
        } catch (Throwable ex) {
            if (process != null) {
                process.destroyForcibly();
            }
            try {
                listener.stopListening(connectorArgs);
            } catch (IOException | IllegalConnectorArgumentsException iex) {
                // ignore
            }
            String text = readFile(crashErrorFile) + readFile(crashOutputFile);
            crashErrorFile.delete();
            crashOutputFile.delete();
            if (text.isEmpty()) {
                throw reportLaunchFail(ex, "listen");
            } else {
                throw new IllegalArgumentException(text);
            }
        }
    }