Retrieve Windows routes through a GetIpForwardTable2 call.

    This is not available on Windows XP !
498429
def _read_routes_c(ipv6=False):
    """"""
    af = socket.AF_INET6 if ipv6 else socket.AF_INET
    sock_addr_name = 'Ipv6' if ipv6 else 'Ipv4'
    sin_addr_name = 'sin6_addr' if ipv6 else 'sin_addr'
    metric_name = 'ipv6_metric' if ipv6 else 'ipv4_metric'
    ip_len = 16 if ipv6 else 4
    if ipv6:
        lifaddr = in6_getifaddr()
    routes = []

    def _extract_ip_netmask(obj):
        ip = obj[sock_addr_name][sin_addr_name]
        ip = bytes(bytearray(ip['byte']))
        # Extract netmask
        netmask = (ip_len - (len(ip) - len(ip.rstrip(b"\x00")))) * 8
        # Build IP
        ip = inet_ntop(af, ip)
        return ip, netmask

    for route in GetIpForwardTable2(af):
        # Extract data
        ifIndex = route['InterfaceIndex']
        _dest = route['DestinationPrefix']
        dest, netmask = _extract_ip_netmask(_dest['Prefix'])
        nexthop, _ = _extract_ip_netmask(route['NextHop'])
        metric = route['Metric']
        # Build route
        try:
            iface = dev_from_index(ifIndex)
            if iface.ip == "0.0.0.0":
                continue
        except ValueError:
            continue
        ip = iface.ip
        # RouteMetric + InterfaceMetric
        metric = metric + getattr(iface, metric_name)
        if ipv6:
            _append_route6(routes, dest, netmask, nexthop,
                           iface, lifaddr, metric)
        else:
            routes.append((atol(dest), itom(int(netmask)),
                           nexthop, iface, ip, metric))
    return routes
911989
def GetForwardedIps(self, interface, interface_ip=None):
    
    try:
      ips = netifaces.ifaddresses(interface)
      ips = ips[netifaces.AF_INET]
    except (ValueError, IndexError):
      return []
    forwarded_ips = []
    for ip in ips:
      if ip['addr'] != interface_ip:
        full_addr = '%s/%d' % (ip['addr'], netaddr.IPAddress(ip['netmask']).netmask_bits())
        forwarded_ips.append(full_addr)
    return self.ParseForwardedIps(forwarded_ips)
880172
public static String extractClientIpFromXForwardedFor(String xForwardedFor) {
        if (xForwardedFor == null) {
            return null;
        }
        xForwardedFor = xForwardedFor.trim();
        String tokenized[] = xForwardedFor.split(",");
        if (tokenized.length == 0) {
            return null;
        } else {
            return tokenized[0].trim();
        }
    }
273119
def nextfreeip(self):
        
        allocated_ips = [ipaddress.ip_address(host['ip']) for host in self.hosts]
        for ip in self.netaddr:
            if str(ip).split('.')[-1] == '0':
                continue
            if ip not in allocated_ips:
                return ip
1263172
private static String getIPAddress () {
    String rc;

    try {
      rc = InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
      // No FFDC code needed
      rc = Long.valueOf(new Random().nextLong()).toString();
    }

    return rc;
  }
386247
def get_router_for_floatingip(self, context, internal_port,
                                  internal_subnet, external_network_id):
        
        gw_port = orm.aliased(models_v2.Port, name="gw_port")
        routerport_qry = context.session.query(
            RouterPort.router_id, models_v2.IPAllocation.ip_address).join(
            models_v2.Port, models_v2.IPAllocation).filter(
            models_v2.Port.network_id == internal_port['network_id'],
            RouterPort.port_type.in_(bc.constants.ROUTER_INTERFACE_OWNERS),
            models_v2.IPAllocation.subnet_id == internal_subnet['id']
        ).join(gw_port, gw_port.device_id == RouterPort.router_id).filter(
            gw_port.network_id == external_network_id,
            gw_port.device_owner == bc.constants.DEVICE_OWNER_ROUTER_GW
        ).distinct()

        # Ensure that redundancy routers (in a ha group) are not returned,
        # since only the user visible router should have floatingips.
        # This can be done by checking that the id of routers does not
        # appear in the 'redundancy_router_id' column in the
        # 'cisco_router_redundancy_bindings' table.
        routerport_qry = routerport_qry.outerjoin(
            RouterRedundancyBinding,
            RouterRedundancyBinding.redundancy_router_id ==
            RouterPort.router_id)
        routerport_qry = routerport_qry.filter(
            RouterRedundancyBinding.redundancy_router_id == expr.null())

        first_router_id = None
        for router_id, interface_ip in routerport_qry:
            if interface_ip == internal_subnet['gateway_ip']:
                return router_id
            if not first_router_id:
                first_router_id = router_id
        if first_router_id:
            return first_router_id

        raise l3_exceptions.ExternalGatewayForFloatingIPNotFound(
            subnet_id=internal_subnet['id'],
            external_network_id=external_network_id,
            port_id=internal_port['id'])
359469
public ActiveTunnel[] getLocalForwardingTunnels(String addressToBind,
			int portToBind) throws IOException {
		return getLocalForwardingTunnels(generateKey(addressToBind, portToBind));
	}
1245531
public java.util.List<IpRouteInfo> getIpRoutesInfo() {
        if (ipRoutesInfo == null) {
            ipRoutesInfo = new com.amazonaws.internal.SdkInternalList<IpRouteInfo>();
        }
        return ipRoutesInfo;
    }
448757
def externalIP()
            joinThread()
            external_ip = getCString()
            r = MiniUPnP.UPNP_GetExternalIPAddress(@urls.controlURL,
                                @data.servicetype,external_ip)
            if r != 0 then
                raise UPnPException.new, "Error while retriving the external ip address. #{code2error(r)}."
            end
            return external_ip.rstrip()
        end
348521
def _findIPAddr(self):
        
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            s.connect(("google.com", 0))
            addr = s.getsockname()[0]
            # print('Using ip : {addr}'.format(addr=addr))
            s.close()
        except socket.error:
            raise NetworkInterfaceException(
                "Impossible to retrieve IP, please provide one manually"
            )
        return addr
296765
def getRoutes(self):
        
        routes = []
        try:
            out = subprocess.Popen([routeCmd, "-n"], 
                                   stdout=subprocess.PIPE).communicate()[0]
        except:
            raise Exception('Execution of command %s failed.' % ipCmd)
        lines = out.splitlines()
        if len(lines) > 1:
            headers = [col.lower() for col in lines[1].split()]
            for line in lines[2:]:
                routes.append(dict(zip(headers, line.split())))
        return routes
1302905
private ChaiProviderImplementor getProviderImpl( )
            throws ChaiUnavailableException
    {
        if ( realProvider != null && !realProvider.isConnected() )
        {
            disconnectRealProvider( "underlying connection has already been closed" );
        }

        switch ( wdStatus )
        {
            case CLOSED:
                throw new IllegalStateException( "ChaiProvider instance has been closed" );

            case ACTIVE:
                return realProvider;

            case IDLE:
                return restoreRealProvider();

            default:
                throw new IllegalStateException( "unexpected internal ProviderState encountered: " + wdStatus );
        }

    }
902913
private AFTPClient actionGetCurrentURL() throws PageException, IOException {
	AFTPClient client = getClient();
	String pwd = client.printWorkingDirectory();
	Struct cfftp = writeCfftp(client);
	cfftp.setEL("returnValue", client.getPrefix() + "://" + client.getRemoteAddress().getHostName() + pwd);
	return client;
    }
796518
function getRoute(route) {
                for (var key in settings.routes) {
                    if (key === route) {
                        return settings.routes[key];
                    }
                }
            }
406732
def get_server_public_ip(server, cached_rules=nil, cached_nat=nil)
      return nil unless server
      # find the public ip
      nic = get_server_default_nic(server)

      ssh_rule = get_ssh_port_forwarding_rule(server, cached_rules)
      return ssh_rule['ipaddress'] if ssh_rule

      winrm_rule = get_winrm_port_forwarding_rule(server, cached_rules)
      return winrm_rule['ipaddress'] if winrm_rule

      #check for static NAT
      if cached_nat
        ip_addr = cached_nat.find {|v| v['virtualmachineid'] == server['id']}
      else
        ip_addr = list_public_ip_addresses.find {|v| v['virtualmachineid'] == server['id']}
      end
      if ip_addr
        return ip_addr['ipaddress']
      end
      if nic.empty?
        return []
      end
      nic['ipaddress'] || []
    end
426378
def _route(self, attr, args, kwargs, **fkwargs):
        

        key = get_key(args, kwargs)

        found = self._hash.get_node(key)

        if not found and len(self._down_connections) > 0:
            raise self.HostListExhausted()

        return [i for i, h in self.cluster.hosts.iteritems()
                if h.identifier == found]
269890
def get_client_address(self, use_x_forwarded=True):
        
        xfor = self.environ.get('HTTP_X_FORWARDED_FOR')
        if use_x_forwarded and xfor:
            return xfor.split(',')[-1].strip()
        else:
            return self.environ['REMOTE_ADDR']