Wednesday, March 8, 2017

Check if connected to internet in Visual Foxpro





? IsInternetConnected('www.example.com')
*-----------------------------------------------------------------------
PROCEDURE IsInternetConnected
LPARAMETERS lcAddress, lcError

LOCAL llSuccess
LOCAL loExc as Exception

IF VARTYPE(gl_ws2_32) <> "L"
  TRY
    DECLARE INTEGER WSACleanup IN ws2_32
    DECLARE STRING inet_ntoa IN ws2_32 INTEGER in_addr
    DECLARE INTEGER gethostbyname IN ws2_32 STRING host
    DECLARE INTEGER WSAStartup IN ws2_32 INTEGER wVerRq, STRING lpWSAData
    DECLARE RtlMoveMemory IN kernel32 As CopyMemory;
   STRING @Dest, INTEGER Src, INTEGER nLength
    PUBLIC gl_ws2_32
    gl_ws2_32 = .T.
    llSuccess = .T.
  CATCH TO loExc
    lcError = TRANSFORM(loExc.ErrorNo) + " " + loExc.Message
  ENDTRY
ELSE
  llSuccess = .T.
ENDIF

IF m.llSuccess AND WSAStartup(0x202, Repli(Chr(0),512)) = 0  && initiates use of WS2_32.DLL
  llSuccess = GetIP('microsoft.com') <> "0.0.0.0"
  = WSACleanup()
ENDIF

RETURN m.llSuccess


*-----------------------------------------------------------------------
FUNCTION GetIP(cServer)
* returns IP like 127.0.0.1 for a given host name like www.somewhere.com
#DEFINE HOSTENT_SIZE 16
 LOCAL nStruct, nSize, cBuffer, nAddr, cIP
 nStruct = gethostbyname(cServer)
 IF nStruct = 0
 * not found in a host database; or not connected etc.
  RETURN '0.0.0.0'
 ENDIF

 cBuffer = Repli(Chr(0), HOSTENT_SIZE)
 cIP = Repli(Chr(0), 4)

 = CopyMemory(@cBuffer, nStruct, HOSTENT_SIZE)
 = CopyMemory(@cIP, buf2dword(SUBS(cBuffer,13,4)),4)
 = CopyMemory(@cIP, buf2dword(cIP),4)
RETURN inet_ntoa(buf2dword(cIP))

FUNCTION buf2dword(lcBuffer)
RETURN Asc(SUBSTR(lcBuffer, 1,1)) + ;
 Bitlshift(Asc(SUBS(lcBuffer, 2,1)),8) +;
 Bitlshift(Asc(SUBS(lcBuffer, 3,1)),16) +;
 Bitlshift(Asc(SUBS(lcBuffer, 4,1)),24)

}

No comments:

Post a Comment