为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
互换的青春 2023-09-16 17:50:21
我添加了以下功能来自动发现内网中的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地址?
查看完整描述

1 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

我认为你的想法是最好的解决方案,通过使用 DNS.GetHostAddress 来获取服务器的实际 IP 地址。它只能由域名系统来完成。DiscoveryClient 仅返回服务器端定义的服务端点地址,该地址仅适用于控制台应用程序托管的服务。


<service name="ConsoleApp3.TestService">

        <!--the below service endpoint address is returned as defined here-->

        <endpoint address="http://10.157.13.69:6666" binding="wsHttpBinding" contract="ConsoleApp3.ITestService" ></endpoint>

        <!--this line code will return domain-->

        <!--<endpoint address="http://vabqia969vm:6666" binding="wsHttpBinding" contract="ConsoleApp3.ITestService"></endpoint>-->

        <!--for exposing the service-->

        <endpoint kind="discoveryEndpoint" address="http://10.157.13.69:6666/exterior" binding="wsHttpBinding" ></endpoint>

      </service>

对于 IIS 中托管的服务,无论站点绑定的类型如何,都仅返回域名。这种情况下,我们就只能利用DNS了。


foreach (EndpointDiscoveryMetadata item in response.Endpoints)

            {

                //retrieve IP address

                System.Net.IPHostEntry hostinfo = System.Net.Dns.GetHostEntry(item.Address.Uri.Host);

                string IPAddress = hostinfo.AddressList[2].ToString();

                Console.WriteLine(IPAddress);

            }

如果有什么需要我帮忙的,请随时告诉我。


查看完整回答
反对 回复 2023-09-16
  • 1 回答
  • 0 关注
  • 49 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信