【问题标题】:How to get hostname using UDP c#如何使用 UDP c# 获取主机名
【发布时间】:2014-04-09 15:47:08
【问题描述】:

我得到了 IP 地址和端口号。现在我需要得到主机名任何建议? 我得到以下代码来获取 ip 和端口号。 静态无效主要(字符串 [] 参数) {

            System.Net.Sockets.UdpClient server = new System.Net.Sockets.UdpClient(15000);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

        byte[] data = new byte[1024];
        data = server.Receive(ref sender);
        server.Close();
        string stringData = Encoding.ASCII.GetString(data, 0, data.Length);


        Console.WriteLine("Response from " + sender.Address + Environment.NewLine + "Port number is " + sender.Port.ToString() + Environment.NewLine + "Message: " + stringData);


        Console.ReadLine();
        }

【问题讨论】:

    标签: c# udp


    【解决方案1】:

    你会想使用DNS.GetHostEntry()

    一些示例代码:

    using System;  
    using System.Net;  
    
    class DNSTest  
    {  
        static void Main()  
        {  
            // Do a few lookups by host name and address  
            DNSLookup("msdn.microsoft.com");  
            DNSLookup("207.46.16.248");  
    
            // Keep the console window open in debug mode  
            Console.WriteLine("Press any key to exit.");  
            Console.ReadKey();  
        }  
    
        protected static void DNSLookup(string hostNameOrAddress)  
        {  
            Console.WriteLine("Lookup: {0}\n", hostNameOrAddress);  
    
            IPHostEntry hostEntry = Dns.GetHostEntry(hostNameOrAddress);  
            Console.WriteLine("  Host Name: {0}", hostEntry.HostName);  
    
            IPAddress[] ips = hostEntry.AddressList;  
            foreach (IPAddress ip in ips)  
            {  
                Console.WriteLine("  Address: {0}", ip);  
            }  
    
            Console.WriteLine();  
        }  
    } 
    

    此代码示例来自here

    【讨论】:

    • 我刚刚使用此代码获得了主机名 Console.WriteLine(Dns.GetHostName());无论如何感谢avitus
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 2019-06-29
    相关资源
    最近更新 更多