Question

I got ip address and port number. Now I need to get hostname any advice? I got following code to get ip and port number. 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();
        }
Was it helpful?

Solution

You would want to use DNS.GetHostEntry()

Some sample code:

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

This code example comes from here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top