-2

I'm trying to complete a project for school that involves me prompting a user for an IP address, then displaying the hostname associated with it. I'm new at C#.

This is my code that I have so far:

        Console.WriteLine("Enter an IP address:"); //prompt user to input IP address
        string host = Console.ReadLine();
        IPHostEntry hostEntry;


        hostEntry = NewMethod(host);

        if (hostEntry.AddressList.Length > 0)
        {
            var ip = hostEntry.AddressList[0];
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            s.Connect(ip, 80);
        }
    }

    private static IPHostEntry NewMethod(string host)
    {
        return Dns.GetHostEntry(host); // NEED FIX
    }
}

The part that has "Need fix" is where the error is showing up. Thanks in advance!

EDIT: How would I be able to display the results in this format: "Host name of x.x.x.x is: hhhhhh", where 'x.x.x.x' is the IP address user entered and 'hhhhh' is the host name of the IP?

EDIT(for StackOverflow): My question is more specific for this instance and is not a general question regarding the NullException issue.

Ryderius
  • 55
  • 5
  • Well you are prompting the user for an input and then you are not asking for anything. `host`is `null` when you call `NewMethod` – InBetween Jan 28 '17 at 15:15
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – InBetween Jan 28 '17 at 15:16
  • @InBetween, I specified why it's not a duplicate and also changed it so that it reads the user input. Thanks! – Ryderius Jan 28 '17 at 15:43
  • Code provided in the post is very unlikely to produce the exception claimed in the title. Please read [MCVE] guidance carefully and avoid code that asks for user input when problem is not related to user input directly. Also make sure to read MSDN (or depending on language of your future questions other sources of documentation) on each method used in sample code to make sure you at least approximately understand what those methods are doing and what values they accept/return. – Alexei Levenkov Jan 28 '17 at 15:49

1 Answers1

0

host is never set, so you're passing null to Dns.GetHostEntry which generates the exception.

At the start of your program it looks like you need to read the IP address from the user:

Console.WriteLine("Enter an IP address:"); //prompt user to input IP address
string host = Console.ReadLine();
Jon Davies
  • 487
  • 4
  • 11