c#Dns.GetHostEntry将不接受字符串. [英] c# Dns.GetHostEntry won't accept a string.

查看:123
本文介绍了c#Dns.GetHostEntry将不接受字符串.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Dns.GetHostEntry或Dns.GetHostAddresses解析主机名.我相信他们俩都会为我提供主机IP.  问题是,每当我传递主机名而不是ipaddress时,它们都会用""

I'm trying to resolve a host name using Dns.GetHostEntry or Dns.GetHostAddresses.  I believe they will both get me the hosts IP.  The problem is whenever i pass a hostname instead of an ipaddress they error out on me with "An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll"

这是代码行:

   IPHostEntry host = Dns.GetHostEntry("localhost");

这是我在C#中的第一个程序,所以我不知道我是否缺少明显的东西.  任何建议将不胜感激.

This is my first program in C# so i don't know if i'm missing something obvious.  Any suggestions would be much appreciated.

谢谢.

Byblyk

推荐答案

来自文档:

如果找不到主机名,则返回SocketException异常,其值为11001(Windows套接字错误WSAHOST_NOT_FOUND).如果DNS服务器没有响应,则可以返回此异常.如果发生以下情况,也可以返回此异常 该名称不是正式的主机名或别名,或者在所查询的数据库中找不到该名称.

If the host name could not be found, the SocketException exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried.

using System;
using System.Net;

class Program
{
    static void Main( string[] args )
    {
        IPHostEntry host = Dns.GetHostEntry( "localhost" );
        Console.WriteLine( host.HostName );
        foreach( var address in host.AddressList ) {
            Console.WriteLine( "{0}: {1}", address.AddressFamily, address.ToString() );
        }
    }
}

这对我来说很好.

此外,很少有人更改其回送适配器.  您要完成什么?

Also, it's pretty rare that anyone changes their loopback adapter.  What are you trying to accomplish?

您很有可能会获得localhost的IPV6地址(:: 1),以及其他主机名的IPV4地址.

It's quite possible that you are getting an IPV6 address (::1) for localhost, and an IPV4 address for other host names.


这篇关于c#Dns.GetHostEntry将不接受字符串.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆