Try to sniff the current client IP.
545307
private function sniff_ip() {

		if ( $this->ip_data ) {
			return;
		}

		if ( PHP_SAPI === 'cli' ) {
			$this->ip_data = [ '127.0.0.1', 'CLI' ];

			return;
		}

		$ip_server_keys = [ 'REMOTE_ADDR' => '', 'HTTP_CLIENT_IP' => '', 'HTTP_X_FORWARDED_FOR' => '',  ];
		$ips            = array_intersect_key( $_SERVER, $ip_server_keys );
		$this->ip_data  = $ips ? [ reset( $ips ), key( $ips ) ] : [ '0.0.0.0', 'Hidden IP' ];
	}
616854
def update(self, ip):
        """"""
        timeout = 60
        LOG.debug("Updating '%s' to '%s' at service '%s'", self.hostname, ip, self._updateurl)
        params = {"myip": ip, "hostname": self.hostname}
        req = requests.get(self._updateurl, params=params, headers=constants.REQUEST_HEADERS_DEFAULT,
                           auth=(self.__userid, self.__password), timeout=timeout)
        LOG.debug("status %i, %s", req.status_code, req.text)
        if req.status_code == 200:
            # responses can also be "nohost", "abuse", "911", "notfqdn"
            if req.text.startswith("good ") or req.text.startswith("nochg"):
                return ip
            return req.text
        return "invalid http status code: %s" % req.status_code
890616
def listen(self, listenip="", listenport=DEF_TFTP_PORT,
               timeout=SOCK_TIMEOUT):
        """"""
        tftp_factory = TftpPacketFactory()

        # Don't use new 2.5 ternary operator yet
        # listenip = listenip if listenip else '0.0.0.0'
        if not listenip: listenip = '0.0.0.0'
        log.info("Server requested on ip %s, port %s" % (listenip, listenport))
        try:
            # FIXME - sockets should be non-blocking
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.sock.bind((listenip, listenport))
            _, self.listenport = self.sock.getsockname()
        except socket.error as err:
            # Reraise it for now.
            raise err

        self.is_running.set()

        log.info("Starting receive loop...")
        while True:
            log.debug("shutdown_immediately is %s" % self.shutdown_immediately)
            log.debug("shutdown_gracefully is %s" % self.shutdown_gracefully)
            if self.shutdown_immediately:
                log.warning("Shutting down now. Session count: %d" %
                         len(self.sessions))
                self.sock.close()
                for key in self.sessions:
                    self.sessions[key].end()
                self.sessions = []
                break

            elif self.shutdown_gracefully:
                if not self.sessions:
                    log.warning("In graceful shutdown mode and all "
                             "sessions complete.")
                    self.sock.close()
                    break

            # Build the inputlist array of sockets to select() on.
            inputlist = []
            inputlist.append(self.sock)
            for key in self.sessions:
                inputlist.append(self.sessions[key].sock)

            # Block until some socket has input on it.
            log.debug("Performing select on this inputlist: %s", inputlist)
            try:
                readyinput, readyoutput, readyspecial = \
                        select.select(inputlist, [], [], SOCK_TIMEOUT)
            except select.error as err:
                if err[0] == EINTR:
                    # Interrupted system call
                    log.debug("Interrupted syscall, retrying")
                    continue
                else:
                    raise

            deletion_list = []

            # Handle the available data, if any. Maybe we timed-out.
            for readysock in readyinput:
                # Is the traffic on the main server socket? ie. new session?
                if readysock == self.sock:
                    log.debug("Data ready on our main socket")
                    buffer, (raddress, rport) = self.sock.recvfrom(MAX_BLKSIZE)

                    log.debug("Read %d bytes", len(buffer))

                    if self.shutdown_gracefully:
                        log.warning("Discarding data on main port, "
                                 "in graceful shutdown mode")
                        continue

                    # Forge a session key based on the client's IP and port,
                    # which should safely work through NAT.
                    key = "%s:%s" % (raddress, rport)

                    if not key in self.sessions:
                        log.debug("Creating new server context for "
                                     "session key = %s" % key)
                        self.sessions[key] = TftpContextServer(raddress,
                                                               rport,
                                                               timeout,
                                                               self.root,
                                                               self.dyn_file_func,
                                                               self.upload_open)
                        try:
                            self.sessions[key].start(buffer)
                        except TftpException as err:
                            deletion_list.append(key)
                            log.error("Fatal exception thrown from "
                                      "session %s: %s" % (key, str(err)))
                    else:
                        log.warning("received traffic on main socket for "
                                 "existing session??")
                    log.info("Currently handling these sessions:")
                    for session_key, session in list(self.sessions.items()):
                        log.info("    %s" % session)

                else:
                    # Must find the owner of this traffic.
                    for key in self.sessions:
                        if readysock == self.sessions[key].sock:
                            log.debug("Matched input to session key %s"
                                % key)
                            try:
                                self.sessions[key].cycle()
                                if self.sessions[key].state == None:
                                    log.info("Successful transfer.")
                                    deletion_list.append(key)
                            except TftpException as err:
                                deletion_list.append(key)
                                log.error("Fatal exception thrown from "
                                          "session %s: %s"
                                          % (key, str(err)))
                            # Break out of for loop since we found the correct
                            # session.
                            break
                    else:
                        log.error("Can't find the owner for this packet. "
                                  "Discarding.")

            log.debug("Looping on all sessions to check for timeouts")
            now = time.time()
            for key in self.sessions:
                try:
                    self.sessions[key].checkTimeout(now)
                except TftpTimeout as err:
                    log.error(str(err))
                    self.sessions[key].retry_count += 1
                    if self.sessions[key].retry_count >= TIMEOUT_RETRIES:
                        log.debug("hit max retries on %s, giving up" %
                            self.sessions[key])
                        deletion_list.append(key)
                    else:
                        log.debug("resending on session %s" % self.sessions[key])
                        self.sessions[key].state.resendLast()

            log.debug("Iterating deletion list.")
            for key in deletion_list:
                log.info('')
                log.info("Session %s complete" % key)
                if key in self.sessions:
                    log.debug("Gathering up metrics from session before deleting")
                    self.sessions[key].end()
                    metrics = self.sessions[key].metrics
                    if metrics.duration == 0:
                        log.info("Duration too short, rate undetermined")
                    else:
                        log.info("Transferred %d bytes in %.2f seconds"
                            % (metrics.bytes, metrics.duration))
                        log.info("Average rate: %.2f kbps" % metrics.kbps)
                    log.info("%.2f bytes in resent data" % metrics.resent_bytes)
                    log.info("%d duplicate packets" % metrics.dupcount)
                    log.debug("Deleting session %s" % key)
                    del self.sessions[key]
                    log.debug("Session list is now %s" % self.sessions)
                else:
                    log.warning(
                        "Strange, session %s is not on the deletion list" % key)

        self.is_running.clear()

        log.debug("server returning from while loop")
        self.shutdown_gracefully = self.shutdown_immediately = False
501839
def check_ip(self):
        
        # For reverse proxy (nginx)
        forwarded_for = self.request.headers.get('X-Forwarded-For', None)
        if forwarded_for:
            return forwarded_for, _check_ip(forwarded_for)

        # For default method
        peer_name = self.request.transport.get_extra_info('peername')
        if peer_name is not None:
            host, _ = peer_name
            return host, _check_ip(host)

        # Not allowed and can't get client IP
        return None, False
1158821
def hasIP(self, ip):
        """"""

        for f in self.features:
            if (f.prop.startswith("net_interface.") and
                    f.prop.endswith(".ip") and f.value == ip):
                return True
        return False
515838
def cli(env, identifier):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)
    global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
                                      name='global ip')
    mgr.unassign_global_ip(global_ip_id)
1307739
def set_current_value(self, value):
        """"""
        self._oldvalue = self.get_current_value()
        self._currentvalue = value
        if self._oldvalue != value:
            # self.notify_observers("new_ip_detected", {"ip": value})
            LOG.debug("%s.set_current_value(%s)", self.__class__.__name__, value)
        return value
1324664
def client_port(self):
        """"""
        address = self._client.getpeername()
        if isinstance(address, tuple):
            return address[1]

        # Maybe a Unix domain socket connection.
        return 0
1168162
def _port_scan_tcp(self, port):
        """"""
        ret = None

        # Create and configure the scanning socket
        try:
            socket.setdefaulttimeout(port['timeout'])
            _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except Exception as e:
            logger.debug("{}: Error while creating scanning socket".format(self.plugin_name))

        # Scan port
        ip = self._resolv_name(port['host'])
        counter = Counter()
        try:
            ret = _socket.connect_ex((ip, int(port['port'])))
        except Exception as e:
            logger.debug("{}: Error while scanning port {} ({})".format(self.plugin_name, port, e))
        else:
            if ret == 0:
                port['status'] = counter.get()
            else:
                port['status'] = False
        finally:
            _socket.close()

        return ret
34553
def local_ip():
    """"""
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith('127.'):
        # Check eth0, eth1, eth2, en0, ...
        interfaces = [
            i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3)
        ]  # :(
        for interface in interfaces:
            try:
                ip = interface_ip(interface)
                break
            except IOError:
                pass
    return ip
464241
def _detect(self):
        """"""
        theip = None
        try:
            if self.opts_family == AF_INET6:
                addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET6]
            else:
                addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET]
        except ValueError as exc:
            LOG.error("netifaces choked while trying to get network interface"
                      " information for interface '%s'", self.opts_iface,
                      exc_info=exc)
        else:  # now we have a list of addresses as returned by netifaces
            for pair in addrlist:
                try:
                    detip = ipaddress(pair["addr"])
                except (TypeError, ValueError) as exc:
                    LOG.debug("Found invalid IP '%s' on interface '%s'!?",
                              pair["addr"], self.opts_iface, exc_info=exc)
                    continue
                if self.netmask is not None:
                    if detip in self.netmask:
                        theip = pair["addr"]
                    else:
                        continue
                else:
                    theip = pair["addr"]
                break  # we use the first IP found
        # theip can still be None at this point!
        self.set_current_value(theip)
        return theip
421891
def get_current_ip(self):
        
        response = get(ICANHAZIP, proxies={"http": self.local_http_proxy})

        if response.ok:
            return self._get_response_text(response)

        raise TorIpError("Failed to get the current Tor IP")
423360
def _get_local_ip(self):
        """"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            # Use Google Public DNS server to determine own IP
            sock.connect(('8.8.8.8', 80))

            return sock.getsockname()[0]
        except socket.error:
            try:
                return socket.gethostbyname(socket.gethostname())
            except socket.gaierror:
                return '127.0.0.1'
        finally:
            sock.close()
1234973
def _ip_is_usable(self, current_ip):
        
        # Consider IP addresses only.
        try:
            ipaddress.ip_address(current_ip)
        except ValueError:
            return False

        # Never use real IP.
        if current_ip == self.real_ip:
            return False

        # Do dot allow IP reuse.
        if not self._ip_is_safe(current_ip):
            return False

        return True
353029
final public static function getClientIp():string
    {
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            return $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            return (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '');
        }
    }
521659
def current(cls):
        
        name = socket.getfqdn()
        ip = socket.gethostbyname(name)

        return cls(name, ip)
454247
public function filter_ip( ){

		// get IP
		$ip = $_SERVER['REMOTE_ADDR'];
		if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}

		return $ip;

	}