利用dig命令查询SRV服务器的方法
1. 什么是SRV
SRV是DNS服务器的数据库中支持的一种资源记录的类型,它记录了哪台计算机提供了哪个服务这么一个简单的信息。在DNS服务器上可以做SRV的配置,使用SRV的好处是需要使用SRV服务的客户端程序不再需要固定SRV服务器的IP地址,这样就增加了灵活性。SRV的详细说明可以参考:http://en.wikipedia.org/wiki/SRV_record
2. 如何解析SRV服务
查询和解析SRV服务可以使用dig命令和nslookup,其中dig既支持windows平台又支持linux平台,是比较好的选择。在各类应用程序中可以通过采用执行系统命令(dig.exe或dig)的方式来解析SRV记录。
3. C# 例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;
namespace SRVTest
{
class Program
{
static void Main(string[] args)
{
string digCmd = "dig.exe";
string srv = "@192.168.0.10 srv _test._tcp.testsrv.com +short";
ArrayList serverList = new ArrayList();
ArrayList outputList = executeCmd(digCmd, srv); //第一次获取SRV服务名称字符串
for (int i = 0; i < outputList.Count; i++)
{
string output = (string)outputList[i];
if (output.Contains("timed out"))
continue;
System.Console.WriteLine("Test srv:" + output);
string[] parts = output.Split(' ');
if (parts.Length < 4)
continue;
string srvName = parts[3];
string srv2 = "@192.168.0.10 " + srvName.Substring(0, srvName.Length - 1) + " " + " +short";
ArrayList outputList2 = executeCmd(digCmd, srv2); //第二次根据SRV服务名称获取对应的IP地址字符串
serverList.AddRange(outputList2);
}
for (int i = 0; i < serverList.Count; i++)
{
string server = (string)serverList[i];
System.Console.WriteLine("server " + i + ": " + server); //真正提供testsrv服务的服务器地址
}
}
//执行系统命令获取输出结果
public static ArrayList executeCmd(String cmdName, String args)
{
ArrayList outputList = new ArrayList();
try
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Maximized;
psi.FileName = cmdName;
psi.Arguments = args;
System.Console.WriteLine("execute command \"" + psi.FileName + " " + psi.Arguments + "\"");
Process prc = Process.Start(psi);
string output = "", errorOutput = "";
while ((output = prc.StandardOutput.ReadLine()) != null)
{
System.Console.WriteLine("Output:" + output);
outputList.Add(output);
}
while ((errorOutput = prc.StandardError.ReadLine()) != null)
{
System.Console.WriteLine("Error output:" + errorOutput);
}
prc.WaitForExit(10000);
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
return outputList;
}
}
}
执行结果:
C:\xxx\dig>SRVTest.exe
execute command "dig.exe @192.168.0.10 srv _test._tcp.testsrv.com +short"
Output:0 0 24633 test200.testsrv.com.
Output:0 0 24633 test201.testsrv.com.
Test srv:0 0 24633 test200.testsrv.com.
execute command "dig.exe @192.168.0.10 test200.testsrv.com +short"
Output:192.168.0.200
Test srv:0 0 24633 test201.testsrv.com.
execute command "dig.exe @192.168.0.2 test201.testsrv.com +short"
Output:192.168.0.201
server 0: 192.168.0.200
server 1: 192.168.0.201