Sunday, December 26, 2010

How do do NSLookup in .NET C#

C# has built in functionality to do NSLookup.  NSLookup is used to return the hostname of an IP Address (simply put).  Here is the code:



public void NSLookup(string arg1)
    {
        this.Label1.Style["text-align"] = "left";


        try
        {
            //The IP or Host Entry to lookup
            IPHostEntry ipEntry;
            //The IP Address Array. Holds an array of resolved Host Names.
            IPAddress[] ipAddr;
            //Value of alpha characters
            char[] alpha = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ-".ToCharArray();
            //If alpha characters exist we know we are doing a forward lookup
            if (arg1.IndexOfAny(alpha) != -1)
            {
                ipEntry = Dns.GetHostEntry(arg1);
                ipAddr = ipEntry.AddressList;
                Console.WriteLine("\nHost Name : " + arg1);
                int i = 0;
                int len = ipAddr.Length;
                for (i = 0; i < len; i++)
                {
                    Console.WriteLine("Address {0} : {1} ", i, ipAddr[i].ToString());
                    Label1.Text = "<b>Address</b> " + i + " : " + ipAddr[i].ToString() + "<br />";
                }
            }
            //If no alpha characters exist we do a reverse lookup
            else
            {
                ipEntry = Dns.GetHostEntry(arg1);
                Label1.Text = "<b>Address</b> : " + arg1 + "<br />";
                Label1.Text += "<b>Host Name</b> : " + ipEntry.HostName + "<br />";
                         
                Console.WriteLine("Address : " + arg1);
                Console.WriteLine("Host Name : " + ipEntry.HostName);
            }
        }
        catch (System.Net.Sockets.SocketException se)
        {
            // The system had problems resolving the address passed
            this.Label1.Style["text-align"] = "center";
            Label1.ForeColor = Color.Maroon;
           
            Label1.Text = "<b>Error</b> : " + se.Message + "<br />";
           
            Console.WriteLine(se.Message.ToString());
        }
        catch (System.FormatException fe)
        {
            this.Label1.Style["text-align"] = "center";
            Label1.ForeColor = Color.Maroon;
            Label1.Text = "<b>Error</b> : " + fe.Message + "<br />";
    
            // Non unicode chars were probably passed 
            Console.WriteLine(fe.Message.ToString());
        }
    }

No comments:

Post a Comment

Generating "Always On Top" NSWindow in macOS across all detected displays

Also: Using UIKit & Cocoa Frameworks using Objective-C In m acOS or OS X , written in either Objective-C or Swift  Langues, you m...