如何在 WCF 自动发现中获取 IP 地址

我添加了以下功能来自动发现内网中的WCF服务。


private void AutoDiscovery(FindCriteria cirteria)

{

    try

    {

        UdpDiscoveryEndpoint udp = new UdpDiscoveryEndpoint();

        using (DiscoveryClient discoveryClient = new DiscoveryClient(udp))

        {

            cirteria.Duration = TimeSpan.FromSeconds(5);

            FindResponse response = discoveryClient.Find(cirteria);

            if (response.Endpoints.Count > 0)

            {

                foreach (EndpointDiscoveryMetadata point in response.Endpoints)

                {

                    string address = point.Address.Uri.ToString();

                    // net.tcp//computer1:8081/wcfService

                }

            }

        }

    }

    catch(Exception e)

    {


    }

}

测试时,返回地址为net.tcp//computer1:8081/wcfService。虽然我可以使用它Dns.GetHostAddress来获取IP地址,但由于DNS问题,在本地内网中需要很长时间。

有没有办法在发现过程中直接获取IP地址?


互换的青春
浏览 52回答 1
1回答

富国沪深

我认为你的想法是最好的解决方案,通过使用 DNS.GetHostAddress 来获取服务器的实际 IP 地址。它只能由域名系统来完成。DiscoveryClient 仅返回服务器端定义的服务端点地址,该地址仅适用于控制台应用程序托管的服务。<service name="ConsoleApp3.TestService">&nbsp; &nbsp; &nbsp; &nbsp; <!--the below service endpoint address is returned as defined here-->&nbsp; &nbsp; &nbsp; &nbsp; <endpoint address="http://10.157.13.69:6666" binding="wsHttpBinding" contract="ConsoleApp3.ITestService" ></endpoint>&nbsp; &nbsp; &nbsp; &nbsp; <!--this line code will return domain-->&nbsp; &nbsp; &nbsp; &nbsp; <!--<endpoint address="http://vabqia969vm:6666" binding="wsHttpBinding" contract="ConsoleApp3.ITestService"></endpoint>-->&nbsp; &nbsp; &nbsp; &nbsp; <!--for exposing the service-->&nbsp; &nbsp; &nbsp; &nbsp; <endpoint kind="discoveryEndpoint" address="http://10.157.13.69:6666/exterior" binding="wsHttpBinding" ></endpoint>&nbsp; &nbsp; &nbsp; </service>对于 IIS 中托管的服务,无论站点绑定的类型如何,都仅返回域名。这种情况下,我们就只能利用DNS了。foreach (EndpointDiscoveryMetadata item in response.Endpoints)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //retrieve IP address&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.Net.IPHostEntry hostinfo = System.Net.Dns.GetHostEntry(item.Address.Uri.Host);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string IPAddress = hostinfo.AddressList[2].ToString();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(IPAddress);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }如果有什么需要我帮忙的,请随时告诉我。
打开App,查看更多内容
随时随地看视频慕课网APP