- Будут ли PHP gethostname и gethostbyname работать всегда?
- gethostbyname() not resolving hostname to ip
- Recommended Answers Collapse Answers
- All 12 Replies
- Функция php gethostbyname() не работает в Linux
- Ответы (1)
- gethostbyname
- Примеры
- Смотрите также
- User Contributed Notes 30 notes
- Функция php gethostbyname() не работает в Linux
- 1 ответы
Будут ли PHP gethostname и gethostbyname работать всегда?
Я разрабатываю приложение PHP, которое необходимо заблокировать для определенного IP-адреса сервера, чтобы люди не могли легко скопировать его на другие серверы. Приложение будет установлено на внутренний сервер в офисе клиента.
У меня есть закодированный файл лицензии с сохраненным в нем разрешенным IP-адресом сервера, и на странице входа я хочу проверить, соответствует ли он IP-адресу сервера.
Для этого я использую следующий код:
if(getHostByName(getHostName()) != $licensedServerIp)
Это прекрасно работает на моем компьютере для разработки, но есть ли какие-либо ситуации, в которых мне нужно следить за тем, чтобы эта функция не работала? Я понятия не имею, что эта функция на самом деле делает в фоновом режиме — могут ли определенные проблемы с сетью помешать ей работать?
Я не уверен, что вижу в этом смысл: это будет проверка локального IP-адреса, такого как 192.168.0.15 , верно? Это будет означать, что любое внутреннее изменение в структуре локальной сети нарушит работу вашего приложения, и можно будет запускать любое количество нелегальных копий в других локальных сетях, пока они получают правильный IP-адрес сервера. Чего это даст, кроме как усложнит жизнь покупателю?
Это не удастся, если сервер не имеет адекватной настройки DNS. Это также не удастся, если кто-то откроет ваш исходный код и удалит проверку. PHP — это язык с открытым исходным кодом, очень сложно заблокировать приложение таким образом — сконцентрируйтесь на зарабатывании денег на поддержке, а не на попытках создать надежную систему лицензирования (потому что ее нет).
Я думаю, что вы поднимаете некоторые очень важные вопросы! Есть ли другой способ остановить выполнение PHP-кода на других серверах?
gethostbyname() not resolving hostname to ip
We have uploaded our cms to a dedicated server. we have two options for our users (user your own domain, use subdomain). when a user register him/her self and select subdomain and want to access his/her website so he cant access it with his/her subdomain name integrated with our domain like (car.websaz.af) instead he can access it with the template name (choosed for his/her website) integrated with our domain name like (temp7.websaz.af). I have created a php file and used gethostbyname() to resolve the hostname to ip but not working.
cod used in the file is as below:
Subdomain ‘tmp12.websaz.af’ resolves to Could someone help me what the problem will be? Thanks in advance
- 4 Contributors
- 12 Replies
- 2K Views
- 3 Weeks Discussion Span
- Latest Post 10 Years Ago Latest Post by aryan200x
Recommended Answers Collapse Answers
What type of server? Linux or Windows? Specifics would help.
@aryan200x
gethostbyname() not resolving hostname to ip
When you used a subdomain it should be in a name of the folder that has your website files.
So when you echo out from a subdomain it should be within the …
@aryan200x
Instead of gethostbyname() function
Try used gethostbyaddr() function.
You need to put property.websaz.af in a folder called property
When you type tmp12.websaz.af/property then it will open.
All 12 Replies
When you used a subdomain it should be in a name of the folder that has your website files. So when you echo out from a subdomain it should be within the folder. For example: The _name is the folder where you put your stuff. This is how you should echo out from the subdomain:
The file containing function gethostbyname is inside public_html and the folders for sub domains are inside websaz_server/HOST/website so I have changed the function as you advised:
but still no luck for ip of that subdomain and it gives me tmp12.websaz.af/websaz_server/HOST/website/w12 Even if I write get google.com not showing its ip address. Does it need any setting in the server? I have put this file to test subdomain resolvation because in our cms when a user creates a website and saves it, when he clicks on his website in the dashboard to manage it, it opens in the browser with this URL tmp12.websaz.af not showing like property.websaz.af but if he type property.websaz.af in the browser then it comes.
@aryan200x Instead of gethostbyname() function Try used gethostbyaddr() function. You need to put property.websaz.af in a folder called property When you type tmp12.websaz.af/property then it will open.
Regarding gethostbyaddr(), this gives the error ‘Warning: gethostbyaddr() [function.gethostbyaddr]: Address is not a valid IPv4 or IPv6 address in /home/websaz/public_html/test.php on line 21. This solution ‘When you type tmp12.websaz.af/property then it will open.’ did not work too. If you know that some settings should be applied on the server then could you please write the instructions? Thanks for helping
Функция php gethostbyname() не работает в Linux
Привет, я хочу получить свой IP-адрес в php, я использую Ubuntu и Apache XAMPP для Linux в качестве веб-сервера.
Когда я выполняю код, он возвращает 127.0.0.1. Я хочу, например, 10.151.32.123. Этот код работает в Windows с xampp, почему этот код не работает в Linux?
В какой именно ситуации вы находитесь? Собираетесь ли вы когда-нибудь разместить этот код на сервере? (Ваш пример, скорее всего, будет работать там.) Или вы хотите использовать его только локально для себя? (Почему бы вам тогда не запрограммировать IP-адрес?) У вас есть маршрутизатор между вами и общедоступным IP-адресом 10.151.32.123 , или это действительно IP-адрес вашего компьютера? Помогает ли вам этот вопрос? — person Phillip   schedule 15.06.2014
спасибо это то что мне нужно. Я просто хочу сделать это локально. — person smidh   schedule 16.06.2014
Ответы (1)
Думаю, это gethostname вас подводит. Попробуйте использовать $_SERVER[‘HTTP_HOST’] или $_SERVER[‘SERVER_NAME’] в вызове gethostbyname .
Сомневаюсь. Почему gethostname не получится? Я предполагаю, что имя хоста отображается на 127.0.0.1 в /etc/hosts (это значение по умолчанию в Ubuntu). — person Phillip; 15.06.2014
Я заменил gethostname на $_SERVER[‘HTTP_HOST’] или $_SERVER[‘SERVER_NAME’], но не повезло, он все равно возвращает 127.0.0.1. — person smidh; 15.06.2014
Да, оглядываясь назад, это было довольно глупо. Сделайте то, что предложил @Phillip, и проверьте файл hosts. — person Dan Cowell; 16.06.2014
gethostbyname
Возвращает адрес IPv4 или строку, содержащую неизмененный hostname в случае возникновения ошибки.
Примеры
Пример #1 Простой пример использования gethostbyname()
$ip = gethostbyname ( ‘www.example.com’ );
?php
Смотрите также
- gethostbyaddr() — Получает доменное имя хоста, соответствующее переданному IP-адресу
- gethostbynamel() — Получает список IPv4-адресов, соответствующих переданному доменному имени хоста
- inet_pton() — Конвертирует читаемый IP-адрес в его упакованное представление in_addr
- inet_ntop() — Конвертирует упакованный интернет-адрес в читаемый формат
User Contributed Notes 30 notes
If you do a gethostbyname() and there is no trailing dot after a domainname that does not resolve, this domainname will ultimately be appended to the server-FQDN by nslookup.
So if you do a lookup for nonexistentdomainname.be your server may return the ip for nonexistentdomainname.be.yourhostname.com, which is the server-ip.
To avoid this behaviour, just add a trailing dot to the domainname; i.e. gethostbyname(‘nonexistentdomainname.be.’)
This function says «Returns the IPv4 address or a string containing the unmodified hostname on failure.
This isn’t entirely true, any hostname with a null byte in it will only return the characters BEFORE the null byte.
$hostname = «foo\0bar» ;
var_dump ( $hostname );
var_dump ( gethostbyname ( $hostname ));
?>
Results:
string ‘foo�bar’ (length=7)
string ‘foo’ (length=3)
Important note: You should avoid its use in production.
DNS Resolution may take from 0.5 to 4 seconds, and during this time your script is NOT being executed.
Your customers may think that the server is slow, but actually it is just waiting for the DNS resolution response.
You can use it, but if you want performance, you should avoid it, or schedule it to some CRON script.
Options for the underlying resolver functions can be supplied by using the RES_OPTIONS environmental variable. (at least under Linux, see man resolv.conf)
Set timeout and retries to 1 to have a maximum execution time of 1 second for the DNS lookup:
putenv ( ‘RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1’ );
gethostbyname ( $something );
?>
You should also use fully qualified domain names ending in a dot. This prevents the resolver from walking though all search domains and retrying the domain with the search domain appended.
For doing basic RBL (Real Time Blacklist) lookups with this function do:
$host = ‘64.53.200.156’ ;
$rbl = ‘sbl-xbl.spamhaus.org’ ;
// valid query format is: 156.200.53.64.sbl-xbl.spamhaus.org
$rev = array_reverse ( explode ( ‘.’ , $host ));
$lookup = implode ( ‘.’ , $rev ) . ‘.’ . $rbl ;
if ( $lookup != gethostbyname ( $lookup )) echo «ip: $host is listed in $rbl \n» ;
> else echo «ip: $host NOT listed in $rbl \n» ;
>
?>
Tomas V.V.Cox
gethostbyname and gethostbynamel does not ask for AAAA records. I have written two functions to implement this. gethostbyname6 and gethostbynamel6. I don’t believe this issue has been addressed yet.
They are made to replace gethostbyname[l], in a way that if $try_a is true, if it fails to get AAAA records it will fall back on trying to get A records.
Feel free to correct any errors, I realise that it is asking for *both* A and AAAA records, so this means two DNS calls.. probably would be more efficient if it checked $try_a before making the query, but this works for me so I’ll leave that up to someone else to implement in their own work.. the tip is out there now anyway..
function gethostbyname6($host, $try_a = false) // get AAAA record for $host
// if $try_a is true, if AAAA fails, it tries for A
// the first match found is returned
// otherwise returns false
function gethostbynamel6($host, $try_a = false) // get AAAA records for $host,
// if $try_a is true, if AAAA fails, it tries for A
// results are returned in an array of ips found matching type
// otherwise returns false
$dns6 = dns_get_record($host, DNS_AAAA);
if ($try_a == true) $dns4 = dns_get_record($host, DNS_A);
$dns = array_merge($dns4, $dns6);
>
else < $dns = $dns6; >
$ip6 = array();
$ip4 = array();
foreach ($dns as $record) if ($record[«type»] == «A») $ip4[] = $record[«ip»];
>
if ($record[«type»] == «AAAA») $ip6[] = $record[«ipv6»];
>
>
if (count($ip6) < 1) if ($try_a == true) if (count($ip4) < 1) return false;
>
else return $ip4;
>
>
else return false;
>
>
else return $ip6;
>
>
When using gethostbynamel() and gethostbyname() together, you must do gethostbynamel() first, otherwise it will always give you one IP (or none) from the cache, and not return the full lookup.
On a side-note, PHP (5.0.4, but probably other versions too) can cache gethostbyname information.
In short, once PHP looks up an address, it may not actually perform another lookup as you may expect. In my particular case (I think) the problem was a change to resolv.conf didn’t take effect inside PHP (although nslookup/ping etc worked fine). Stop/Starting Apache fixed it (although a simple ‘restart’ (kill -HUP) didn’t).
In short, if you change resolv.conf, stop and restart Apache.
In PHP4 you can use gethostbyname() but I have found this unreliable when doing lookups on entries that return A records on the private network. PHP5 has a much better routine — dns_get_record(). If you are stuck with PHP4 or don’t want to upgrade you can use dig:
Функция php gethostbyname() не работает в Linux
Привет, я хочу получить свой IP-адрес в php, я использую Ubuntu и Apache XAMPP для Linux в качестве веб-сервера.
Когда я выполняю код, он возвращает 127.0.0.1. Я хочу, например, 10.151.32.123. Этот код работает в Windows с xampp, почему этот код не работает в Linux?
В какой именно ситуации вы находитесь? Собираетесь ли вы когда-нибудь разместить этот код на сервере? (Ваш пример, скорее всего, будет работать там.) Или вы хотите использовать его только локально для себя? (Почему бы вам тогда жестко не указать IP-адрес?) У вас есть маршрутизатор между вами и общедоступным IP-адресом? 10.151.32.123 , или это действительно IP вашего компьютера? Делает этот связанный вопрос помочь тебе? — Phillip
спасибо это то что мне нужно. Я просто хочу сделать это локально. — smidh
1 ответы
Это gethostname который подводит вас здесь, я думаю. Попробуйте использовать $_SERVER[‘HTTP_HOST’] or $_SERVER[‘SERVER_NAME’] в вашем звонке gethostbyname .
Сомневаюсь. Почему должен gethostname неудача? Я предполагаю, что имя хоста отображается на 127.0.0.1 в /etc/hosts (это по умолчанию в Ubuntu). — Филипп
Я заменил gethostname на $_SERVER[‘HTTP_HOST’] или $_SERVER[‘SERVER_NAME’], но не повезло, он все равно возвращает 127.0.0.1. — середина
Да, оглядываясь назад, это было довольно глупо. Сделайте то, что предложил @Phillip, и проверьте файл hosts. — Дэн Коуэлл
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками php linux ubuntu or задайте свой вопрос.