c# - Getting error on Host to IP conversion if I don't have connectivity - Help! :-)

Greetings Experts,

I have the following code:

                IPAddress[] addresslist = Dns.GetHostAddresses("www.google.com");
                foreach (IPAddress theaddress in addresslist)
                {
                    MessageBox.Show(theaddress.ToString());
                }

Which works GREAT.... as long as I actually have network connectivity, but when I don't have network connectivity, as I would suspect, I get an error on the following line:

 IPAddress[] addresslist = Dns.GetHostAddresses("www.google.com");

Which makes sense to me, because the app wouldn't have access to dns without network connectivity...

But.. my question is... how do I handle the error? what I would like to do, in the event of an error would be to:
            theaddress = "1.1.1.1";

So, the Question is, how do I handle the error, and as a result of the error, set theaddress to "1.1.1.1"?

Thanks!
MiShepsAsked:
Who is Participating?
 
RishadanPortConnect With a Mentor Commented:
try{
   IPAddress[] addresslist = Dns.GetHostAddresses("www.google.com");
}
catch(Exception e){
   //set addresslist to whatever you want here
}
0
 
MiShepsAuthor Commented:
Nope, didn't work
0
 
MiShepsAuthor Commented:
scratch that, I just didn't understand that "try" was part of the code, figured it out though, and your solution works well, with a small bit added.

Good help, thanks for the info!

Here is what I ended up with:

                bool SkipServerIPConvert;
 
                // Convert IP for "Other" Server
                // #############################
                SkipServerIPConvert == false;
                try
                {
                    IPAddress[] addresslist = Dns.GetHostAddresses(MyGlobalVariables.OtherServer);
                }
                catch (Exception e)
                {
                    MyGlobalVariables.OtherServer = "1.1.1.1";
                    SkipServerIPConvert = true;
                }
                if (SkipServerIPConvert == false)
                {
                    IPAddress[] addresslist = Dns.GetHostAddresses(MyGlobalVariables.OtherServer);
                    foreach (IPAddress theaddress in addresslist)
                    {
                        MyGlobalVariables.OtherServer = theaddress.ToString();
                    }
                }
                // #############################

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.