Link to home
Start Free TrialLog in
Avatar of MiSheps
MiShepsFlag for United States of America

asked on

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!
ASKER CERTIFIED SOLUTION
Avatar of RishadanPort
RishadanPort

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MiSheps

ASKER

Nope, didn't work
Avatar of MiSheps

ASKER

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