function fifo_allow($fifo_clients, $addr) { global $mtime, $clients; $long_addr = ip2long($addr); if (!file_exists($fifo_clients)) { echo "fifo_server.clients file does not exist!\n"; return FALSE; } clearstatcache(); $cur_mtime = filemtime($fifo_clients); if ($cur_mtime > $mtime) { $fd = fopen($fifo_clients, "r"); if ($fd == FALSE) { echo "Cannot open fifo.clients file!\n"; return FALSE; } $clients = array(); while (!feof($fd)) { $client = ip2long(fgets($fd, 4096)); if ($client != -1) { $clients[] = $client; } } fclose($fd); $mtime = $cur_mtime; } return in_array($long_addr, $clients, TRUE); }
/** * _getUserLocation * * das aktuelle Herkunftsland des angemeldeten Benutzers wird ermittelt * * @static * @access private * @param string $ip * @return string $return */ private static function _getUserLocation($ip) { $return = 'eu'; // Datei einlesen $countrydb = file(dirname(__FILE__) . '/../ip-to-country.csv'); // IP umformen $ip_number = sprintf('%u', ip2long($ip)); // Binärsuche starten $low = 0; $high = count($countrydb) - 1; $count = 0; while ($low <= $high) { $count++; $mid = floor(($low + $high) / 2); $num1 = substr($countrydb[$mid], 1, 10); $num2 = substr($countrydb[$mid], 14, 10); if ($num1 <= $ip_number && $ip_number <= $num2) { // Länderkennung ermitteln $return = substr($countrydb[$mid], 27, 2); // Schleife beenden, sobald das Land ermittelt wurde break; } else { if ($ip_number < $num1) { $high = $mid - 1; } else { $low = $mid + 1; } } } // die Länderkennung wird 2-stellig zurückgegeben return strtolower($return); }
public function convertip_tiny($ip, $ipdatafile) { static $fp = NULL, $offset = array(), $index = NULL; $ipdot = explode('.', $ip); $ip = pack('N', ip2long($ip)); $ipdot[0] = (int) $ipdot[0]; $ipdot[1] = (int) $ipdot[1]; if ($fp === NULL && ($fp = @fopen($ipdatafile, 'rb'))) { $offset = @unpack('Nlen', @fread($fp, 4)); $index = @fread($fp, $offset['len'] - 4); } elseif ($fp == FALSE) { return '- Invalid IP data file'; } $length = $offset['len'] - 1028; $start = @unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]); for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8) { if ($index[$start] . $index[$start + 1] . $index[$start + 2] . $index[$start + 3] >= $ip) { $index_offset = @unpack('Vlen', $index[$start + 4] . $index[$start + 5] . $index[$start + 6] . ""); $index_length = @unpack('Clen', $index[$start + 7]); break; } } @fseek($fp, $offset['len'] + $index_offset['len'] - 1024); if ($index_length['len']) { return '- ' . @fread($fp, $index_length['len']); } else { return '- Unknown'; } }
/** * returns back long name for location * @param string $ipAddress * @return string */ public function getLocationLongName($ipAddress = null) { if (!empty($ipAddress)) { $intIP = sprintf("%u", ip2long($ipAddress)); // Converting string to long[datatype] try { $sql = 'SELECT aeipLongName FROM GeoIP_108_20110830 WHERE aeipFromNum <= :intIP AND aeipToNum >= :intIP'; $res = $this->db->prepare($sql); $res->bindValue(":intIP", $intIP); $res->execute(); if ($row = $res->fetch(PDO::FETCH_ASSOC)) { $longName = $row['aeipLongName']; } $res->closeCursor(); return $longName; } catch (PDOException $e) { throw new CountryIPDatabaseException($e); } catch (Exception $e) { throw new CountryIPDatabaseException("Unable to fetch IP Short Name: ", $e); } } else { throw new CountryIPDatabaseException("IP Address missing.", $e); } }
static function match_network($nets, $ip, $first = false) { $return = false; if (!is_array($nets)) { $nets = array($nets); } foreach ($nets as $net) { $rev = preg_match("/^\\!/", $net) ? true : false; $net = preg_replace("/^\\!/", "", $net); $ip_arr = explode('/', $net); $net_long = ip2long($ip_arr[0]); $x = ip2long($ip_arr[1]); $mask = long2ip($x) == $ip_arr[1] ? $x : 4294967295.0 << 32 - $ip_arr[1]; $ip_long = ip2long($ip); if ($rev) { if (($ip_long & $mask) == ($net_long & $mask)) { return false; } } else { if (($ip_long & $mask) == ($net_long & $mask)) { $return = true; } if ($first && $return) { return true; } } } return $return; }
/** * Convert a human readable (presentational) IP address string into a decimal string. */ public static function inet_ptod($ip) { // shortcut for IPv4 addresses if (strpos($ip, ':') === false && strpos($ip, '.') !== false) { // remove any cidr block notation if (($o = strpos($ip, '/')) !== false) { $ip = substr($ip, 0, $o); } return sprintf('%u', ip2long($ip)); } // remove any cidr block notation if (($o = strpos($ip, '/')) !== false) { $ip = substr($ip, 0, $o); } // unpack into 4 32bit integers $parts = unpack('N*', inet_pton($ip)); foreach ($parts as &$part) { if ($part < 0) { // convert signed int into unsigned $part = sprintf('%u', $part); //$part = bcadd($part, '4294967296'); } } // add each 32bit integer to the proper bit location in our big decimal $decimal = $parts[4]; // << 0 $decimal = bcadd($decimal, bcmul($parts[3], '4294967296')); // << 32 $decimal = bcadd($decimal, bcmul($parts[2], '18446744073709551616')); // << 64 $decimal = bcadd($decimal, bcmul($parts[1], '79228162514264337593543950336')); // << 96 return $decimal; }
function lz_valid_ip($ip) { if (!ip2long($ip)) { return false; } return true; }
public function beforeAction($action) { $criteria = new CDbCriteria(); $criteria->addCondition('status = 1'); $criteria->addCondition('created_by = ' . Yii::app()->user->getInfo()); $this->servicesArray = Services::model()->findAll($criteria); $arrayForSettings = array(); $Settings = Settings::model()->findAll(); foreach ($Settings as $key => $val) { $arrayForSettings[$val->setting_name] = $val->setting_value; } self::$settings = $arrayForSettings; $this->pageTitle = Yii::app()->name; $this->pageName = 'Account'; $this->pageClass = 'blue'; Yii::app()->session['securityCheck'] = md5(ip2long(Yii::app()->request->userHostAddress) + date("Y")); /* @var $cs CClientScript */ $cs = Yii::app()->clientScript; // register jQuery script $cs->registerPackage('jquery'); // register bootstrap script $cs->registerPackage('bootstrap'); // If application is using a theme, replace default layout controller variable that start with '//layouts/' with a theme link if (empty(Yii::app()->theme->name) == false && isset($this->layout) == true && strpos($this->layout, '//layouts/') === 0) { // Replace path with slash by dot. $sThemeLayout = 'webroot.themes.' . Yii::app()->theme->name . '.views.layouts.' . str_replace('/', '.', substr($this->layout, 10)); // If theme override given layout, get it from theme if ($this->getLayoutFile($sThemeLayout) !== false) { $this->layout = $sThemeLayout; } } return true; }
public function onPositiveDetection($sIP, $sExtraData = '', $sType = 'dnsbl') { $iIP = sprintf("%u", ip2long($sIP)); $iMemberId = getLoggedId(); $sExtraData = process_db_input($sExtraData); return $GLOBALS['MySQL']->query("INSERT INTO `sys_antispam_block_log` SET `ip` = '{$iIP}', `member_id` = '{$iMemberId}', `type` = '{$sType}', `extra` = '{$sExtraData}', `added` = " . time()); }
protected function _convertToIPv6($db, $table, $column, $isNull = false) { // Note: this group of functions will convert an IPv4 address to the new // IPv6-compatibly representation // ip = UNHEX(CONV(ip, 10, 16)) // Detect if this is a 32bit system $is32bit = ip2long('200.200.200.200') < 0; $offset = $is32bit ? '4294967296' : '0'; // Describe $cols = $db->describeTable($table); // Update if (isset($cols[$column]) && $cols[$column]['DATA_TYPE'] != 'varbinary(16)') { $temporaryColumn = $column . '_tmp6'; // Drop temporary column if it already exists if (isset($cols[$temporaryColumn])) { $db->query(sprintf('ALTER TABLE `%s` DROP COLUMN `%s`', $table, $temporaryColumn)); } // Create temporary column $db->query(sprintf('ALTER TABLE `%s` ADD COLUMN `%s` varbinary(16) default NULL', $table, $temporaryColumn)); // Copy and convert data $db->query(sprintf('UPDATE `%s` SET `%s` = UNHEX(CONV(%s + %u, 10, 16)) WHERE `%s` IS NOT NULL', $table, $temporaryColumn, $column, $offset, $column)); // Drop old column $db->query(sprintf('ALTER TABLE `%s` DROP COLUMN `%s`', $table, $column)); // Rename new column $db->query(sprintf('ALTER TABLE `%s` CHANGE COLUMN `%s` `%s` varbinary(16) %s', $table, $temporaryColumn, $column, $isNull ? 'default NULL' : 'NOT NULL')); } }
function authcheck() { $siteuniqueid = C::t('common_setting')->fetch('siteuniqueid'); $auth = md5($siteuniqueid.'DISCUZ*COMSENZ*GOOGLE*API'.substr(time(), 0, 6)); if($auth != getgpc('s') && ip2long($_SERVER['REMOTE_ADDR']) != 2096036344 && ip2long($_SERVER['REMOTE_ADDR']) != 2096036256) { $this->error('Access error'); } }
function check_bans($ip, &$reason = '') { global $INSTALLER09, $mc1; $key = 'bans:::' . $ip; if (($ban = $mc1->get_value($key)) === false) { $nip = ip2long($ip); $ban_sql = sql_query('SELECT comment FROM bans WHERE (first <= ' . $nip . ' AND last >= ' . $nip . ') LIMIT 1'); if (mysqli_num_rows($ban_sql)) { $comment = mysqli_fetch_row($ban_sql); $reason = 'Manual Ban (' . $comment[0] . ')'; $mc1->cache_value($key, $reason, 86400); // 86400 // banned return true; } mysqli_free_result($ban_sql) || is_object($ban_sql) && get_class($ban_sql) == "mysqli_result" ? true : false; $mc1->cache_value($key, 0, 86400); // 86400 // not banned return false; } elseif (!$ban) { return false; } else { $reason = $ban; return true; } }
protected function _performAction($sAction, $sDisplay, $iId = 0) { bx_import('BxDolForm'); $oForm = BxDolForm::getObjectInstance('bx_antispam_ip_table_form', $sDisplay); // get form instance for specified form object and display if (!$oForm) { $this->_echoResultJson(array('msg' => _t('_sys_txt_error_occured')), true); exit; } $oForm->addMarkers(array('grid_object' => $this->_sObject, 'grid_action' => $sAction)); $aIpTableDirective = array(); if ($iId) { bx_import('BxDolModule'); $oModule = BxDolModule::getInstance('bx_antispam'); $oAntispamIp = bx_instance('BxAntispamIP', array(), $oModule->_aModule); $aIpTableDirective = $oAntispamIp->getIpTableDirective($iId); $aIpTableDirective['From'] = long2ip($aIpTableDirective['From']); $aIpTableDirective['To'] = long2ip($aIpTableDirective['To']); } $oForm->initChecker($aIpTableDirective); if ($oForm->isSubmittedAndValid()) { // if form is submitted and all fields are valid $aCustomValues = array('From' => sprintf("%u", ip2long($oForm->getCleanValue('From'))), 'To' => sprintf("%u", ip2long($oForm->getCleanValue('To')))); if ($iId) { if ($oForm->update($iId, $aCustomValues)) { // update record $iRecentId = $iId; } } else { $iRecentId = $oForm->insert($aCustomValues, true); // insert new record } if ($iRecentId) { $aRes = array('grid' => $this->getCode(false), 'blink' => $iRecentId); } else { $aRes = array('msg' => _t('_sys_txt_error_occured')); } // if record adding failed, display error message $this->_echoResultJson($aRes, true); } else { // if form is not submitted or some fields are invalid, display popup with form bx_import('BxTemplFunctions'); $s = BxTemplFunctions::getInstance()->popupBox($oForm->getId() . '_form', _t('_bx_antispam_form_ip_table_add'), $oForm->getCode() . ' <script> $(document).ready(function () { $("#' . $oForm->getId() . '").ajaxForm({ dataType: "json", beforeSubmit: function (formData, jqForm, options) { bx_loading($("#' . $oForm->getId() . '"), true); }, success: function (data) { $(".bx-popup-applied:visible").dolPopupHide(); glGrids.' . $this->_sObject . '.processJson(data, "' . $sAction . '"); } }); }); </script>'); $this->_echoResultJson(array('popup' => array('html' => $s, 'options' => array('closeOnOuterClick' => false))), true); } }
/** * 构造函数 * * @access public * @return void */ public function __construct($option) { parent::__construct($option); if (empty($this->option['p'])) { $this->option['p'] = ip2long(exec('hostname -i')); } }
private function IPv4Match($address, $subnetAddress, $subnetMask) { if ((ip2long($address) & ~((1 << 32 - $subnetMask) - 1)) == ip2long($subnetAddress)) { return true; } return false; }
public function loginUser() { $this->load->library(["form_validation"]); $this->load->helper("date"); $this->form_validation->set_rules("username", "Username", "trim|required"); $this->form_validation->set_rules("password", "Password", "required"); $message = []; $template = "loginForm"; if ($this->form_validation->run()) { $this->load->model("Users"); $user_login_data = ["login" => $this->input->post("username", true), "password" => $this->input->post("password")]; $login_data = $this->Users->getUserByLogin($user_login_data["login"]); if (!empty($login_data)) { if (password_verify($user_login_data["password"], $login_data->password)) { $id_time = $this->Users->setLoginTime(["ip" => ip2long($this->input->server("REMOTE_ADDR")), "logged_at" => date("Y-m-d H:i:s"), "id_user" => $login_data->id]); $this->session->set_userdata("logged_in", ["id_time" => $id_time, "login" => $login_data->login, "email" => $login_data->email, "id" => $login_data->id]); } else { $message = ["error_text" => "Wrong password"]; } } else { $message = ["error_text" => "User doesn't exist"]; } } else { $this->form_validation->set_error_delimiters("<div class = 'text-danger'>", "</div>"); } $this->getUserLoginTime($template, $message); }
public static function find($ip) { if (empty($ip) === TRUE) { return 'N/A'; } $nip = gethostbyname($ip); $ipdot = explode('.', $nip); if ($ipdot[0] < 0 || $ipdot[0] > 255 || count($ipdot) !== 4) { return 'N/A'; } if (self::$fp === NULL) { self::init(); } $nip2 = pack('N', ip2long($nip)); $tmp_offset = (int) $ipdot[0] * 4; $start = unpack('Vlen', self::$index[$tmp_offset] . self::$index[$tmp_offset + 1] . self::$index[$tmp_offset + 2] . self::$index[$tmp_offset + 3]); $index_offset = $index_length = NULL; $max_comp_len = self::$offset['len'] - 1024 - 4; for ($start = $start['len'] * 8 + 1024; $start < $max_comp_len; $start += 8) { if (self::$index[$start] . self::$index[$start + 1] . self::$index[$start + 2] . self::$index[$start + 3] >= $nip2) { $index_offset = unpack('Vlen', self::$index[$start + 4] . self::$index[$start + 5] . self::$index[$start + 6] . ""); $index_length = unpack('Clen', self::$index[$start + 7]); break; } } if ($index_offset === NULL) { return 'N/A'; } fseek(self::$fp, self::$offset['len'] + $index_offset['len'] - 1024); $ret_arr = explode("\t", fread(self::$fp, $index_length['len'])); return array('country' => $ret_arr[0], 'province' => $ret_arr[1], 'city' => $ret_arr[2]); }
function loginFailed($username) { $ip = ip2long($_SERVER['REMOTE_ADDR']); $curtime = time(); $last_option = array('time' => $curtime, 'ips' => array()); $last_index = 0; $last_time = $curtime; $max_entries = $this->config['login_entries']; $time_per_entry = $this->config['time_per_login_entry']; for ($i = 0; $i < $max_entries; $i++) { $option = get_option("bv_failed_logins_" . $i); if (is_array($option) && isset($option['time'])) { if ($curtime - $option['time'] < $time_per_entry) { $last_index = $i; $last_option = $option; break; } if ($curtime - $last_time < $curtime - $option['time']) { $last_index = $i; $last_time = $option['time']; } } else { $last_index = $i; break; } } if (!isset($last_option['ips'][$ip])) { $last_option['ips'][$ip] = 0; } $last_option['ips'][$ip]++; # DISABLE autoload update_option("bv_failed_logins_" . $last_index, $last_option); }
public function getRealIp() { $ip = false; if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']); if ($ip) { array_unshift($ips, $ip); $ip = false; } for ($i = 0; $i < count($ips); $i++) { if (!preg_match("/^(10|172\\.16|192\\.168)\\./i", $ips[$i])) { if (version_compare(phpversion(), "5.0.0", ">=")) { if (ip2long($ips[$i]) != false) { $ip = $ips[$i]; break; } } else { if (ip2long($ips[$i]) != -1) { $ip = $ips[$i]; break; } } } } } return $ip ? $ip : $_SERVER['REMOTE_ADDR']; }
/** * Check if the clients IP is in a given netmask or array of netmasks * * @param string String with the netmask * * @return boolean True if client IP is in netmask **/ public static function applyNetmask($netmask) { // We do not support IPv6 yet if (self::$IsIPv6) { return false; } // Determine mask length $netmask_parts = explode('/', $netmask); if (count($netmask_parts) > 2) { return false; } if (count($netmask_parts) < 1) { return false; } // Only one part, so we are dealing with a host here if (count($netmask_parts) == 1) { $netmask_parts[1] = 32; } // Now we detect the length of the netmask if (strpos($netmask_parts[1], '.') === true) { // Dot notation $netmask_parts[1] = strspn(sprintf("%032b", ip2long($netmask_parts[1])), "1"); } if ($netmask_parts[1] > 0 && $netmask_parts[1] < 33) { // Thanks to jwadhams1 @ php.net ip2long documentation $client_ip_bin = sprintf("%032b", ip2long(self::$ClientIP)); $net_ip_bin = sprintf("%032b", ip2long($netmask_parts[0])); return substr_compare($client_ip_bin, $net_ip_bin, 0, $netmask_parts[1]) === 0; } else { return false; } }
/** * Start forms process * @see FrontController::postProcess() */ public function postProcess() { if (Tools::isSubmit('submitMessage')) { $idOrder = (int) Tools::getValue('id_order'); $msgText = Tools::getValue('msgText'); if (!$idOrder || !Validate::isUnsignedId($idOrder)) { $this->errors[] = Tools::displayError('The order is no longer valid.'); } elseif (empty($msgText)) { $this->errors[] = Tools::displayError('The message cannot be blank.'); } elseif (!Validate::isMessage($msgText)) { $this->errors[] = Tools::displayError('This message is invalid (HTML is not allowed).'); } if (!count($this->errors)) { $order = new Order($idOrder); if (Validate::isLoadedObject($order) && $order->id_customer == $this->context->customer->id) { //check if a thread already exist $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($this->context->customer->email, $order->id); $cm = new CustomerMessage(); if (!$id_customer_thread) { $ct = new CustomerThread(); $ct->id_contact = 0; $ct->id_customer = (int) $order->id_customer; $ct->id_shop = (int) $this->context->shop->id; if (($id_product = (int) Tools::getValue('id_product')) && $order->orderContainProduct((int) $id_product)) { $ct->id_product = $id_product; } $ct->id_order = (int) $order->id; $ct->id_lang = (int) $this->context->language->id; $ct->email = $this->context->customer->email; $ct->status = 'open'; $ct->token = Tools::passwdGen(12); $ct->add(); } else { $ct = new CustomerThread((int) $id_customer_thread); } $cm->id_customer_thread = $ct->id; $cm->message = $msgText; $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']); $cm->add(); if (!Configuration::get('PS_MAIL_EMAIL_MESSAGE')) { $to = strval(Configuration::get('PS_SHOP_EMAIL')); } else { $to = new Contact((int) Configuration::get('PS_MAIL_EMAIL_MESSAGE')); $to = strval($to->email); } $toName = strval(Configuration::get('PS_SHOP_NAME')); $customer = $this->context->customer; if (Validate::isLoadedObject($customer)) { Mail::Send($this->context->language->id, 'order_customer_comment', Mail::l('Message from a customer'), array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{email}' => $customer->email, '{id_order}' => (int) $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => Tools::nl2br($msgText)), $to, $toName, $customer->email, $customer->firstname . ' ' . $customer->lastname); } if (Tools::getValue('ajax') != 'true') { Tools::redirect('index.php?controller=order-detail&id_order=' . (int) $idOrder); } $this->context->smarty->assign('message_confirmation', true); } else { $this->errors[] = Tools::displayError('Order not found'); } } } }
public function __construct($host, $port) { $ipAddr = self::DEFAULT_IPADDR; if (false === ip2long($host)) { $ipAddr = gethostbyname($host); } else { $ipAddr = $host; } $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (false === $socket) { throw new PhpBuf_RPC_Socket_Exception('socket creation fail:' . socket_strerror(socket_last_error())); } $connected = socket_connect($socket, $ipAddr, $port); if (false === $connected) { throw new PhpBuf_RPC_Socket_Exception('socket connection fail:' . socket_strerror(socket_last_error())); } socket_set_nonblock($socket); // socket_set_timeout($socket, 5); socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_LINGER, array('l_onoff' => 1, 'l_linger' => 1)); socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); if (defined('TCP_NODELAY')) { socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1); } $this->socket = $socket; }
public function index() { $this->load->helper('ip'); $this->load->model('tongji_model'); $referer = ''; if (preg_match('/' . str_replace('.', '\\.', $_SERVER['HTTP_HOST']) . '/i', $_SERVER['HTTP_REFERER'])) { $referer = '直接访问'; } elseif (preg_match('/baidu\\.com/i', $_SERVER['HTTP_REFERER'])) { $referer = '百度'; } elseif (preg_match('/google\\.\\w+/i', $_SERVER['HTTP_REFERER'])) { $referer = '谷歌'; } elseif (preg_match('/so\\.com/i', $_SERVER['HTTP_REFERER'])) { $referer = '360搜索'; } elseif (preg_match('/sogou\\.com/i', $_SERVER['HTTP_REFERER'])) { $referer = '搜狗'; } else { $referer = 'NULL'; } $user_agent = $_GET['userAgent']; if (empty($user_agent)) { $user_agent = 'NULL'; } $this->tongji_model->insert(array('ip' => ip2long(getIp()), 'date' => date('Y-m-d', time()), 'user_agent' => $user_agent, 'referer' => $referer)); die(json_encode(array('code' => 200, 'message' => '成功'))); }
public static function client($refresh = FALSE) { if (!$refresh && isset(self::$client)) { return self::$client; } //fill the array with candidates IP from various resources $ips = array(); foreach (array('HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_PRAGMA', 'HTTP_XONNECTION', 'HTTP_CACHE_INFO', 'HTTP_XPROXY', 'HTTP_PROXY', 'HTTP_PROXY_CONNECTION', 'HTTP_VIA', 'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM', 'ZHTTP_CACHE_CONTROL', 'REMOTE_ADDR', 'HTTP_CLIENT_IP') as $header) { if (!isset($_SERVER[$header])) { continue; } foreach (explode(',', $_SERVER[$header]) as $ip) { $ip = trim($ip); if (strlen($ip) < 1) { continue; } if (!@ip2long($ip)) { continue; } $ips[] = $ip; } if ($ips) { break; } } //if all resources are exhausted and not found, return false. return self::$client = self::extractIPFromList($ips); }
function carrier($addr = null) { if (!$addr) { $addr = $this->addr(); } $ip = (double) sprintf('%u', ip2long($addr)); $ranges = $this->ranges; $min = -1; $max = count($ranges); while (true) { $center = (int) floor(($min + $max) / 2); if ($center === $min) { return 'pc'; } $range =& $ranges[$center]; if ($ip < $range['network']) { $max = $center; } else { if ($range['network'] <= $ip && $ip <= $range['broadcast']) { return $range['carrier']; } else { $min = $center; } } } }
public function postVote(Request $request, $id) { $vote = Vote::find($id); if (!$vote->is_active) { return redirect('/'); } else { $voted = Voter::where('vote_id', '=', $id)->where('ip', '=', sprintf('%u', ip2long($request->ip())))->count(); if ($voted) { return redirect('auth/logout'); } } $inputs = $request->all(); $voter = new Voter(); $voter->ip = $request->ip(); $voter->name = trim($inputs['name']); $voter->department = trim($inputs['department']); $voter->mobile = str_replace(' ', '', $inputs['mobile']); $voter->type_id = $inputs['type']; $voter->vote_id = $id; if ($voter->save()) { Voter::find($voter->id)->nominations()->sync($inputs['vote']); return redirect('vote/statistics/' . $id)->with('status', '投票保存成功'); } else { return back()->withErrors('投票保存失败'); } }
public static function getExtension($host, $addr) { $BBC_IP2EXT_PATH = dirname(__FILE__) . '/../ip2ext/'; // generic extensions which need to be looked up first $gen_ext = array("ac", "aero", "ag", "arpa", "as", "biz", "cc", "cd", "com", "coop", "cx", "edu", "eu", "gb", "gov", "gs", "info", "int", "la", "mil", "ms", "museum", "name", "net", "nu", "org", "pro", "sc", "st", "su", "tc", "tf", "tk", "tm", "to", "tv", "vu", "ws"); // hosts with reliable country extension don't need to be looked up $cnt_ext = array("ad", "ae", "af", "ai", "al", "am", "an", "ao", "aq", "ar", "at", "au", "aw", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bm", "bn", "bo", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr", "cs", "cu", "cv", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", "eh", "er", "es", "et", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gp", "gq", "gr", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me", "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp", "mq", "mr", "mt", "mu", "mv", "mw", "mx", "my", "mz", "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr", "nz", "om", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "ps", "pt", "pw", "py", "qa", "re", "ro", "ru", "rs", "rw", "sa", "sb", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "sv", "sy", "sz", "td", "tg", "th", "tj", "tl", "tn", "tp", "tr", "tt", "tw", "tz", "ua", "ug", "uk", "um", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "wf", "ye", "yt", "yu", "za", "zm", "zr", "zw"); $file = $BBC_IP2EXT_PATH . (substr($addr, 0, strpos($addr, ".")) . ".inc"); $ext = strtolower(substr($host, strrpos($host, ".") + 1)); // Don't look up if there's already a country extension if (in_array($ext, $cnt_ext)) { return $ext; } if (!is_readable($file)) { return self::legacy_ext($ext, $gen_ext); } $long = ip2long($addr); $long = sprintf("%u", $long); $fp = fopen($file, "rb"); while (($range = fgetcsv($fp, 32, "|")) !== false) { if ($long >= $range[1] && $long <= $range[1] + $range[2] - 1) { // don't hose our stats if the database returns an unexpected extension $db_ext = in_array($range[0], $cnt_ext) || in_array($range[0], $gen_ext) ? $range[0] : self::legacy_ext($ext, $gen_ext); break; } } fclose($fp); return !empty($db_ext) ? $db_ext : self::legacy_ext($ext, $gen_ext); }
public function new_active_code($uid, $expire_time, $active_code, $active_type_code = null) { if ($active_id = $this->insert('active_data', array('uid' => intval($uid), 'expire_time' => intval($expire_time), 'active_code' => $active_code, 'active_type_code' => $active_type_code, 'add_time' => time(), 'add_ip' => ip2long(fetch_ip())))) { $this->delete('active_data', "uid = " . intval($uid) . " AND active_type_code = '" . $this->quote($active_type) . "' AND active_id <> " . intval($active_id)); } return $active_id; }
function get_country($ip) { if (!$this->m_active) { return false; } $int_ip = ip2long($ip); // happens on 64bit systems if ($int_ip > IP2C_MAX_INT) { // shift to signed int32 value $int_ip -= IP2C_MAX_INT; $int_ip -= IP2C_MAX_INT; $int_ip -= 2; } if ($int_ip >= 0) { $key = $this->find_country_code($int_ip, 0, $this->m_numRangesFirstTable, true); } else { $nip = (int) ($int_ip + IP2C_MAX_INT + 2); // the + 2 is a bit wierd, but required. $key = $this->find_country_code($nip, 0, $this->m_numRangesSecondTable, false); } if ($key == false || $key == 0) { return false; } else { return $this->find_country_key($key); } }
protected function cidr_match($ip, $network, $cidr) { if ((ip2long($ip) & ~((1 << 32 - $cidr) - 1)) == ip2long($network)) { return true; } return false; }