如何使用UDP c#获取主机名

时间:2014-04-09 01:53:33

标签: c# udp

我有ip地址和端口号。现在我需要获得主机名的任何建议吗? 我得到以下代码来获取ip和端口号。  static void Main(string [] args)             {

            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();
        }

1 个答案:

答案 0 :(得分:0)

您可能希望使用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