PHP DNS resolver - php

I need to resolve dns.
Here is my cmd command:
host -a google.com 8.8.8.8
or
(host -a s4.artemisweb.jp ns0.domain_name.com
host -a s4.artemisweb.jp 77.88.8.1)
and it returns something like that:
root#min /etc # host -a google.com 8.8.8.8
Trying "google.com"
;; Truncated, retrying in TCP mode.
Trying "google.com"
Using domain server:
Name: 8.8.8.8
Address: 8.8.8.8#53
Aliases:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 6364
;; flags: qr rd ra; QUERY: 1, ANSWER: 24, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com. IN ANY
;; ANSWER SECTION:
google.com. 300 IN A 74.125.232.103
google.com. 300 IN A 74.125.232.96
google.com. 300 IN A 74.125.232.102
google.com. 300 IN A 74.125.232.97
for my further work i need
74.125.232.103 74.125.232.96 etc. ip addresses.(answer section)
Actually php has
$result = dns_get_record("php.net", DNS_ANY, $authns, $addtl);
but I also have second parameter
"8.8.8.8" or "ns0.domain_name.com or 77.88.8.1"
(and with this additional parameters "host" command returns different IP) and there is no place for it in command above.

Use nslookup instead simplier output and each ip has Address: at the front so easy to regex
[root#sid ~]# nslookup www.google.com
Server: 10.0.0.253
Address: 10.0.0.253#53
Non-authoritative answer:
Name: www.google.com
Address: 74.125.24.99
Name: www.google.com
Address: 74.125.24.147
Name: www.google.com
Address: 74.125.24.104
Name: www.google.com
Address: 74.125.24.103
Name: www.google.com
Address: 74.125.24.106
Name: www.google.com
Address: 74.125.24.105

Here is the answer:
$resolver = new Net_DNS_Resolver();
$resolver->debug = 1; // Turn on debugging output to show the query
$resolver->usevc = 1; // Force the use of TCP instead of UDP
$resolver->nameservers = array( // Set the IP addresses
'198.41.0.4', // of the nameservers
'192.228.79.201' // to query.
);
$response = $resolver->query('example.com');
if (! $response) {
echo "\n";
echo "ANCOUNT is 0, therefore the query() 'failed'\n";
echo "See Net_DNS_Resolver::rawQuery() to receive this packet\n";
}
?>

Related

PHP: how get answer from a UDP server

I'm tryng to implement this discovery message for Yeelight lamp (link to manual: http://www.yeelight.com/download/Yeelight_Inter-Operation_Spec.pdf)
The searching message generated by 3rd device should follow below format and rules and
being sent to multi-cast address 239.255.255.250:1982 over UDP.
-------------------------------------------------------------
M-SEARCH * HTTP/1.1
HOST: 239.255.255.250:1982
MAN: "ssdp:discover"
ST: wifi_bulb
-------------------------------------------------------------
1. The start line must be "M-SEARCH * HTTP/1.1" without any leading LWP.
2. "HOST" header is optional, if it's present, the value should be "239.255.255.250:1982".
3. "MAN" header is required. The value for "MAN" header must be "ssdp:discover",
double quotes included.
4. "ST" header is required. The value for "ST" header must be "wifi_bulb".
5. The headers are case-insensitive while the start line and all the header values are case
sensitive. Each line should be terminated by "\r\n".
I admit: I'm not able to work with socket, so I did try and failed (no answer, on var dump only "int(116)").
$discover_message = "M-SEARCH * HTTP/1.1\r\n
HOST: 239.255.255.250:1982\r\n
MAN: \"ssdp:discover\"\r\n
ST: wifi_bulb\r\n";
$socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or die("Cannot create a socket");
socket_connect($socket,'239.255.255.250','1982') or die("Couldnot connect to socket");
$ret = socket_sendto($socket,$discover_message,strlen($discover_message),0,'239.255.255.250','1982');
socket_set_nonblock($socket);
var_dump($ret);
I did try also add
$socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or die("Cannot create a socket");
socket_connect($socket,'239.255.255.250','1982') or die("Couldnot connect to socket");
$ret = socket_sendto($socket,$discover_message,strlen($discover_message),0,'239.255.255.250','1982');
socket_set_nonblock($socket);
var_dump($ret);
$sec = 0;
$usec = $sec === null ? null : (($sec - floor($sec)) * 1000000);
$r = array($socket);
while (socket_select($r, $x, $x, $sec, $usec)) {
$data = socket_read($socket, 4096, PHP_BINARY_READ);
var_dump($data);
}
(reading how implemented on another github project, this one uses a packagist socket that wrapper socket itself)
but I get the int(116) again.
The answer need to be (as stated by manual)
-------------------------------------------------------------
HTTP/1.1 200 OK
Cache-Control: max-age=3600
Date:
Ext:
Location: yeelight://192.168.1.239:55443
Server: POSIX UPnP/1.0 YGLC/1
id: 0x000000000015243f
model: color
fw_ver: 18
support: get_prop set_default set_power toggle set_bright start_cf stop_cf set_scene
cron_add cron_get cron_del set_ct_abx set_rgb
power: on
bright: 100
color_mode: 2
ct: 4000
rgb: 16711680
hue: 100
sat: 35
name: my_bulb
-------------------------------------------------------------
How get my list of lamp, as stated on the manual?
Thank you

php - ssh2_exec failed allocating pty

Using PHP, I need to periodically execute a remote command on a Draytek 2925 router using SSH.
I can already connect to the router using the standard "ssh" command on Linux, but after authenticating I am getting "PTY allocation request failed on channel 0". However despite that message, I can still send commands.
When I try doing the same with PHP, I am getting 1 of 2 results and neither of which is returning the results I need.
My code is as follows:
<?
if (!($connection = ssh2_connect('my.router.local', 22)))
die('CONN');
else if (!ssh2_auth_password($connection, 'admin', 'password'))
die('AUTH');
else
{
$stream = ssh2_exec($connection, 'sys version');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);
exit();
}
?>
The PHP fails at ssh2_exec(). If I specify the 3rd argument (pty), I get this result:
Warning: ssh2_exec(): Failed allocating 1 pty at 80x25 characters
However, not specifying the 3rd argument results in:
Warning: ssh2_exec(): Unable to request command execution on remote host
Even if I type #ssh2_exec(), I don't get a warning, but I don't get a result either.
If PHP is a no-go, I tried using sshpass in the same way, but that results in the following:
# sshpass -f sshpwd -v ssh admin#my.router.local 'sys version'
SSHPASS searching for password prompt using match "assword"
SSHPASS read: admin#my.router.local's password:
SSHPASS detected prompt. Sending password.
SSHPASS read:
exec request failed on channel 0
#
I ultimately just need to authenticate, send a command and return the result. Is there anything I am doing wrong or is there a simpler way?
I have resolved my query by using TELNET instead. Yes it's not secure like SSH, but since it's being used internally over the LAN, it doesn't matter.
For anyone interested, I used Net_Telnet and the following code:
<?php
require_once "Net/Telnet.php";
$router = 'my.router.local';
$password = 'password';
try
{
$t = new Net_Telnet($router);
$t->connect();
$t->login([
'login_prompt' => 'Account:',
'login_success' => ' User login successful, expired time is "Unlimited".',
'login_fail' => '% Access denied',
'login' => 'admin',
'password' => $password,
'prompt' => "{$router}>",
]
);
echo $t->cmd('sys version');
$t->disconnect();
// catch any buffered data
echo $t->get_data();
echo "\n";
} catch (Exception $e)
{
echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";
}
exit();
?>
Which results in:
# php -f telnet.php
sys version
Router Model: Vigor2925n Version: 3.8.4 English
Profile version: 3.0.0 Status: 1 (0x48245e4c)
Router IP: 0.0.0.0 Netmask: 255.255.255.0
Firmware Build Date/Time: Dec 15 2016 17:26:01
Router Name: my.router.local
Revision: 61327 V384_2925
>
#

Freeradius - Receive data from external script

I am using Freeradius v3 for my project, and I am executing an external php script to do some checks in the authorization section. What I am trying to achieve is to get multiple attribute-value pairs from the script like:
Auth-Type (control) : value Reply-Message (reply) : value ...
So, for example, i would like to receive and Auth-Type = Accept plus a Reply-Message from the script.
I used this post: FreeRadius Reading attributes while executing external script as reference, and I tried to do as suggested but it isn't working.
Here is some code to explain what I'm doing:
1 - Authorize section
authorize{
update{
control: += `/usr/bin/php -f /path/to/script/test.php '%{User-Name}'`
}
....
2 - Php script (echo section)
echo "Auth-Type = Accept,\n";
echo "reply:WISPr-Redirection-URL = http://google.com,\n";
echo "reply:Reply-Message = 'hello world'\n";
3 - Php output (as suggested from the linked post)
Auth-Type = Accept
reply:WISPr-Redirection-URL = http://google.com
reply:Reply-Message = 'hello world'
4 - Freeradius output
Proxying to virtual server test-server
(0) # Executing section authorize from file /etc/freeradius/sites-enabled/test-server
(0) authorize {
(0) update {
(0) Executing: /usr/bin/php -f /path/to/script/test.php '%{User-Name}':
(0) EXPAND %{User-Name}
(0) --> alice
(0) ERROR: Failed parsing output from: /usr/bin/php -f /home/saiv/radius_script/test.php '%{User-Name}': Expecting operator
(0) ERROR: Program returned code (0) and output 'Auth-Type = Accept, reply:WISPr-Redirection-URL = http://google.com, reply:Reply-Message = 'hello world''
(0) } # update = fail
(0) } # authorize = fail
If I remove the "reply:Reply-Message ..." and put only "Reply-Message:..." the output is accepted by freeradius but the Reply-Message avp goes under "control" and this is not correct.
(0) Program returned code (0) and output 'Auth-Type = Accept, WISPr-Redirection-URL = http://google.com, Reply-Message = 'hello world''
(0) control::Auth-Type = Accept
(0) control::WISPr-Redirection-URL = http://google.com
(0) control::Reply-Message = hello world
Can someone tell me what I am missing?
Any help would be appreciated.

How to get domain expires date using whois response data on php?

How to get domain expires date using whois response data on php ?
Normally i use whois response for check domain availability.
eg: check DRGDRGDRGRGDRG.COM if whois response data have word No match for it's mean this domain is available.
No match for domain "DRGDRGDRGRGDRG.COM".
But now i want to check domain expires date using whois response data like this
Domain Name: GOOGLE.COM
Registrar: MARKMONITOR INC.
Sponsoring Registrar IANA ID: 292
Whois Server: whois.markmonitor.com
Referral URL: http://www.markmonitor.com
Name Server: NS1.GOOGLE.COM
Name Server: NS2.GOOGLE.COM
Name Server: NS3.GOOGLE.COM
Name Server: NS4.GOOGLE.COM
Status: clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited
Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited
Status: clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited
Status: serverDeleteProhibited https://icann.org/epp#serverDeleteProhibited
Status: serverTransferProhibited https://icann.org/epp#serverTransferProhibited
Status: serverUpdateProhibited https://icann.org/epp#serverUpdateProhibited
Updated Date: 20-jul-2011
Creation Date: 15-sep-1997
Expiration Date: 14-sep-2020
How can i do that ? thank you
This is not a simple question of parsing the response string as it might sound at the first moment because domain name registrars provide information in different format.
I guess we have two options here:
Use some library and when it fails parse the string
Do everything yourself, do not use any library and parse the output.
I suggest to start with some library but I really do not know the 'perfect' one. I'm going to try phpWhois. If it fails it gives raw data to try and parse it on our own.
First you need to install the library. I do this using Composer. Below is my composer.json file
{
"require": {
"phpwhois/phpwhois":"dev-master",
"mso/idna-convert": "0.9.1"
}
}
Note that latest phpWhois version does not work with latest idna-convert version, this is why I have to specify it in my requirements.
Execute composer install to download the libraries.
And finally PHP script to query the domain:
<?php
require(__DIR__ . '/vendor/autoload.php');
use phpWhois\Whois;
$whois = new Whois();
$whois->deepWhois = true;
$query = isset($argv[1]) ? $argv[1] : 'google.com';
$result = $whois->lookup($query);
$registered = isset($result['regrinfo']['registered']) && $result['regrinfo']['registered'] == 'yes';
if (!$registered) {
echo 'Domain: '.$query.' not registered.'.PHP_EOL;
} else {
if (isset($result['regrinfo']['domain']['expires'])) {
echo 'Domain: '.$query.PHP_EOL;
echo 'Expired: '.$result['regrinfo']['domain']['expires'].PHP_EOL;
} else {
echo 'Domain: '.$query.PHP_EOL;
echo 'Trying to find expires date...'.PHP_EOL;
foreach ($result['rawdata'] as $raw) {
if (strpos($raw, 'Expiry Date:') !== false) {
echo 'Expired: '.trim(explode(':', $raw)[1]).PHP_EOL;
}
}
}
}
It takes domain name as the first script argument $argv[1].
If the library does not parse the results from registrar we try to parse it manually. I've added a simple check
if (strpos($raw, 'Expiry Date:') !== false) {
echo 'Expired: '.trim(explode(':', $raw)[1]).PHP_EOL;
}
You might search for 'Expiration Date' in the raw response data or do some better logic based on your experience with parsing data if you will. Perfectly the library should do this but sometimes it fails.

PHP - get server to ping a visitors IP and return the ping in ms

I want to do as the title states. To ping a users IP and return a result in ms, for instance:
Ping IP
return 400ms.
I have no idea how to do this but I expect it would be relatively simple. I have access to the exec() function and the functions similar to it as I will be running this script on a virtual private server.
Thanks in advance.
try this
<?php
$out = array();
exec('ping -c 4 '.$_SERVER['REMOTE_ADDR'], $out);
print_r($out);
?>
Try this:
<?php
$ip = $_SERVER['SERVER_ADDR']; // Get the IP address of the visitor
$result = system('ping -n 1 '.$ip, $retval); // the result contains the last line of the ping command.
if ($retval==0) echo "OK";
if ($retval==1) echo "NOT OK";
?>

Categories