I run a Minecraft website and currently when using the query protocol it can't work with SRV records.
I am just wondering is there a way to get the ip and port that the SRV record points to.
E.g: mc.lunarphase.co.uk => 192.198.91.238:64759
The easiest way is probably to use dig. You could use sockets directly but something like this is easier (IMHO):
function getDNS($hostname, $type='') {
$records=`dig +noall +answer $hostname $type`;
$records=explode("\n",$records);
$res_hostname='';
$port=0;
foreach ($records as $record) {
preg_match_all('/([^\s]+)\s*/',$record, $matches);
if (is_array($matches) && is_array($matches[1]) && count($matches[1]) > 3) {
switch (strtoupper($matches[1][3])) {
case 'SRV':
if (count($matches[1]) > 6) {
$port=$matches[1][6];
$res_hostname=$matches[1][7];
}
break;
case 'A':
case 'CNAME':
if (count($matches[1]) > 3) {
$res_hostname=$matches[1][4];
}
break;
}
if (!empty($res_hostname) && substr($res_hostname, -1) == '.') break; // if it's a cname, we've probably already got the ip, so keep going just in case (but we might not so don't count on it!)
}
}
if (substr($res_hostname, -1) == '.') { // we have more resolving to do
$res_hostname=getDNS(trim($res_hostname, '. '));
}
if (empty($res_hostname)) die('Failed to lookup IP for ' . (!empty($type) ? '(' . $type .' record) ' : '' ) . $hostname . PHP_EOL);
if (empty($port)) return $res_hostname;
return $res_hostname . ':' . $port;
}
$hostIPPair=getDNS('example.com', 'srv');