4

I am working on a Winforms application and using C# as the development language. In one place I need to send a request to a URL and receive the feedback.

I use my code within a try catch block and I catch the WebException. I noticed WebException occures due to 2 reasons.

(1) when the URL I entered is wrong(A url that does not exist)

(2) When there is no internet connection

So is that okay If I catch the WebException in a situation where the URL is correct, to check that the local machine does not have internet connection. (I need to check that the internet connection exists or not to continue the next step)

Can anyone confirm that my suggestion is correct or if wrong why? Thanks inadvance

JibW
  • 4,538
  • 17
  • 66
  • 101

2 Answers2

2

You can't check for Internet connection by trying to connect to an URL. You can't tell between a bad connection or the server not available.

There is a win32 API in wininet - see check whether Internet connection is available with C#

Community
  • 1
  • 1
bryanmac
  • 38,941
  • 11
  • 91
  • 99
1

I used this function (in vb .net) to know if internet is available:

Public Function HasInternet() As Boolean
    Dim response As Boolean = False
    Try
        response = My.Computer.Network.Ping("www.google.com")
        If Not response Then
            'Try another one
            response = My.Computer.Network.Ping("www.yahoo.com")
        End If
    Catch ex As Exception
        'Catch the error or leave it blank for returning False
    End Try
    Return response
End Function

The only problem is if google.com and yahoo.com stop aswering ping's requests, it will report no internet connection.

Esselans
  • 1,540
  • 2
  • 24
  • 44
  • 1
    Note that many sites/routers etc... will block ICMP. As an example, from my current machine that I'm adding this comment for, I have internet connection but I can't ping google or yahoo. – bryanmac Jan 26 '12 at 16:26
  • This helped me. Thank you – SamyCode Sep 13 '18 at 14:24