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

本文关键字:取主机名 UDP 何使用 | 更新日期: 2023-09-27 17:57:40

我得到了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();
        }

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

您想要使用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();  
    }  
} 

这个代码示例来自这里