c# - dns.gethostbyname()

标签 c# .net dns ipv4

网上查了dns gethostbyname改成gethostentry,修改了代码,为什么还是不能显示正常的ipv4地址? 这是我的代码:

string GetHostIP()
    {      
        String myHostName = System.Net.Dns.GetHostName();

        // Find host by name
        System.Net.IPHostEntry myiphost = System.Net.Dns.GetHostEntry(myHostName);

        String ipstring = "";
        foreach(System.Net.IPAddress myipadd in myiphost.AddressList)
        {
            ipstring = myipadd.ToString();
            return ipstring;
        }
        return ipstring;
    }

最佳答案

他们试图让您停止假设 IP 地址是点分十进制 IPv4 地址。他们只是无法让 IPv6 落地,而这是必要的。几个月前完全没有免费地址。

你可以获得 IPv4 地址,你必须明确地把它捞出来:

        foreach (System.Net.IPAddress myipadd in myiphost.AddressList) {
            if (myipadd.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
                return myipadd.ToString();

            }
        }
        throw new WhatTheHeckException();

关于c# - dns.gethostbyname(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7532842/

相关文章:

ubuntu - EC2 Ubuntu : unable to access site from browser but able to access from EC2 ubuntu terminal

c# - 找不到数据时是否返回一个空的通用列表?

c# - 有没有办法阻止 Visual Studio 2008 默认在设计 View 中打开文件?

c# - 使用由 MEF 加载的模型类型的 ASP.Net MVC View 导致 View 构建器中的 JIT 编译错误

c# - 无法对 SQL Server Express 2008 使用 SQL Server 身份验证

.net - 在 SQL Server 中共享来自单个数据库的程序集(模拟 GAC)

c# - 在 WPF 中构建可逆的 StackPanel

java - 通过Java检查域名年龄

python - 重定向所有对 www 的请求。到根域

c# - ServiceStack OrmLite - 从存储过程中捕获 Sql InfoMessage 事件