如何在C#中从给定的IP地址获取域名?

13

我希望从给定的 IP 中获取域名。 例如,如果我提供的 IP 是“172.24.17.85”,那么我应该只得到类似于我的域名 sonata.net。

有没有 C# 的代码片段可以实现这个功能?

4个回答

33

你尝试过使用Dns.GetHostEntry吗?

例子:

using System;
using System.Net;

class Test
{
    static void Main(string[] args)
    {
        IPAddress addr = IPAddress.Parse("69.59.196.211");
        IPHostEntry entry = Dns.GetHostEntry(addr);
        Console.WriteLine(entry.HostName); // Prints "stackoverflow.com"
    }
}

请注意,这并不适用于您提供的示例...如果反向DNS查找无法正常工作,我不确定您能做什么。


1
Console.WriteLine("DomainName: {0}", Dns.GetHostEntry("1.1.1.1").HostName);

你好Jon,你的代码运行良好,但问题是当我输入任何外部IP或我的本地IP时,我可以得到域名,但如果我尝试输入局域网中存在的任何机器的IP,则返回给我IP地址而不是域名。 请帮帮我... - Swapnil Gupta
@Swapnil:尝试从命令行进行反向查找nslookup [ip地址],并查看该IP地址的结果。此外,您可以尝试使用Dns.GetHostAddresses;http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses.aspx - KMån
在命令提示符中使用这个命令会给我返回其他的地址,而如果我使用“let address”,就会得到域名。 那么问题出在哪里呢?我不明白。 - Swapnil Gupta

1

我真的怀疑这是否可能。可能有n个域名指向同一个IP地址。您可以在反向DNS查找上进行一些研究。


0

这是一个完整的程序,基于@Jon Skeets的答案,但包含输入/输出文件。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace IP_reverse_checker
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // based on source: https://stackoverflow.com/a/44040867/6584859
            // based on source: https://dev59.com/R3A75IYBdhLWcg3wg5Zh#3252871

            Regex ip = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");

            Console.WriteLine(">>> IP reverse checker <<<");
            Console.WriteLine();
            Console.WriteLine("Please enter the complete path to the text file containing the list of IP addresses:");
            string fileNameInput = @"" + Console.ReadLine();

            // Lets remove leading/trailing double quotes, if present:
            char[] trimChars = { '"' };
            string cleanFileNameInput = fileNameInput.Trim(trimChars);

            int numberFileLines = 0;
            string[] inputLines = new string[] { };

            try
            {
                inputLines = File.ReadAllLines(cleanFileNameInput);
                numberFileLines = inputLines.Length;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error reading the file!  error: " + ex.Message);
                Console.WriteLine();
                Console.WriteLine("Press ENTER to exit the program.");
                Console.ReadLine();
                Environment.Exit(0);
            }

            List<string> outputLines = new List<string>();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("The file contains " + numberFileLines + " lines. I start processing...");
            Console.WriteLine();

            int counter = 0;

            foreach (string line in inputLines)
            {
                counter++;

                try
                {
                    MatchCollection result = ip.Matches(line);

                    if (result[0].Success)
                    {
                        string hostName = "";
                        IPAddress addr = IPAddress.Parse(line);

                        try
                        {
                            IPHostEntry entry = Dns.GetHostEntry(addr);
                            hostName = entry.HostName;
                        }
                        catch (Exception)
                        {
                            hostName = ">> No Reverse-DNS entry found!";
                        }

                        if (hostName != "")
                        {
                            outputLines.Add(line + " | " + hostName);
                            Console.WriteLine("line " + counter + " of " + numberFileLines + ": " + line + " | " + hostName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error processing line " + counter + "  -  error: " + ex.Message);
                }
            }

            if (outputLines.Count > 0)
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Done! " + outputLines.Count + " IP adresses were processed.");
                Console.WriteLine();
                Console.WriteLine("Please enter the complete path to the text file where the list with IP addresses AND hostnames should be stored:");

                string fileNameOutput = @"" + Console.ReadLine();
                string cleanFileNameOutput = fileNameOutput.Trim(trimChars);

                try
                {
                    File.AppendAllLines(cleanFileNameOutput, outputLines);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error writing the file!  error: " + ex.Message);
                }

                Console.WriteLine();
                Console.WriteLine("Done! Output file was written. Please press ENTER to exit the program.");
                Console.ReadLine();
            }
        }
    }
}


输入文件应该是这样一个格式的示例:
10.0.10.126
10.0.10.17
10.0.20.120
10.0.20.126
10.0.20.127
10.0.20.138
10.0.20.139

输出文件将看起来像这个例子:

10.0.10.126 | Thinkpad23.dnssuffix
10.0.10.17 | desktop63.dnssuffix
10.0.20.120 | Thinkpad16.dnssuffix
10.0.20.126 | Thinkpad08.dnssuffix
10.0.20.127 | desktop19.dnssuffix
10.0.20.138 | Thinkpad04.dnssuffix
10.0.20.139 | Thinkpad09.dnssuffix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接