Change gethostbyname() with dns_get_record()

This commit is contained in:
Deon George 2022-03-25 21:50:58 +11:00
parent 8072f7c5a9
commit 0fe65d6187

View File

@ -58,7 +58,7 @@ final class SocketClient {
public function __construct (\Socket $connection) {
socket_getsockname($connection,$this->address_local,$this->port_local);
socket_getpeername($connection,$this->address_remote,$this->port_remote);
Log::info(sprintf('%s:+ Connection from [%s] on port [%d]',self::LOGKEY,$this->address_remote,$this->port_remote));
Log::info(sprintf('%s:+ Connection host [%s] on port [%d]',self::LOGKEY,$this->address_remote,$this->port_remote));
$this->connection = $connection;
}
@ -226,32 +226,53 @@ final class SocketClient {
* Create a client socket
* @param string $address
* @param int $port
* @param int $speed
* @return static
* @throws SocketException
*/
public static function create(string $address,int $port,int $speed=self::TCP_SPEED): self
public static function create(string $address,int $port): self
{
Log::debug(sprintf('%s:+ Creating connection to [%s:%d]',self::LOGKEY,$address,$port));
$sort = collect(['AAAA','A']);
$address = gethostbyname($address);
// We only look at AAAA/A records
$resolved = collect(dns_get_record($address,DNS_AAAA|DNS_A))
->filter(function($item) use ($sort) { return $sort->search(Arr::get($item,'type')) !== FALSE; })
->sort(function($item) use ($sort) { return $sort->search(Arr::get($item,'type')); });
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if ($socket === FALSE)
throw new SocketException(SocketException::CANT_CREATE_SOCKET,socket_strerror(socket_last_error($socket)));
if (! $resolved->count())
throw new SocketException(SocketException::CANT_CONNECT,sprintf('%s doesnt resolved to an IPv4/IPv6 address',$address));
try {
$result = socket_connect($socket,$address,$port);
$result = FALSE;
} catch (\ErrorException $e) {
throw new SocketException(SocketException::CANT_CONNECT,socket_strerror(socket_last_error($socket)));
foreach ($resolved as $address) {
try {
$try = Arr::get($address,Arr::get($address,'type') == 'AAAA' ? 'ipv6' : 'ip');
if (! $try)
continue;
Log::alert(sprintf('%s: - Trying [%s:%d]',self::LOGKEY,$try,$port));
/* Create a TCP/IP socket. */
$socket = socket_create(Arr::get($address,'type') == 'AAAA' ? AF_INET6 : AF_INET,SOCK_STREAM,SOL_TCP);
if ($socket === FALSE)
throw new SocketException(SocketException::CANT_CREATE_SOCKET,socket_strerror(socket_last_error($socket)));
$result = socket_connect($socket,$try,$port);
break;
} catch (\ErrorException $e) {
// If 'Cannot assign requested address'
if (socket_last_error($socket) == 99)
continue;
throw new SocketException(SocketException::CANT_CONNECT,socket_strerror(socket_last_error($socket)));
}
}
if ($result === FALSE)
throw new SocketException(SocketException::CANT_CONNECT,socket_strerror(socket_last_error($socket)));
return new self($socket,$speed);
return new self($socket);
}
/**