Lazarus

Programming => General => Topic started by: Nicole on February 03, 2023, 01:33:44 pm

Title: is there an internet connection?
Post by: Nicole on February 03, 2023, 01:33:44 pm
I took a method out of some source and have no idea, how it works:

Code: Pascal  [Select][+][-]
  1. function InternetConnected: Boolean;
  2.  
  3. var
  4.   dwConnectionTypes: DWord;
  5. begin
  6.   dwConnectionTypes := INTERNET_CONNECTION_MODEM or INTERNET_CONNECTION_LAN or INTERNET_CONNECTION_PROXY;
  7.   Result := InternetGetConnectedState(@dwConnectionTypes, 0);
  8. end;

What I want to: Check, if the internet connection exists.
The check produces false positives.

Any ideas, why this may be?

At the moment it starts from within a VMWare-VM under Win 7 and has a NAT connection.
Title: Re: is there an internet connection?
Post by: TRon on February 03, 2023, 01:38:58 pm
Always try to read the original documentation first. It helps in understanding what the function is suppose to do.

https://learn.microsoft.com/en-us/windows/win32/api/wininet/nf-wininet-internetgetconnectedstate

There it states:
Quote
Note  Using this API is not recommended, use the INetworkListManager::GetConnectivity method instead.

Title: Re: is there an internet connection?
Post by: howardpc on February 03, 2023, 01:42:33 pm
See this   (https://forum.lazarus.freepascal.org/index.php/topic,43819.msg307232.html#msg307232)answer, and the others in the same thread
Title: Re: is there an internet connection?
Post by: Nicole on February 03, 2023, 01:44:47 pm
Thank you for the link.
The problem is: I do not understand the details. Neither in "my" source, nor in the links.

Do you think, you can just copy me the correct line form there?
The only thing I need, is a result only true, if there is a connection.

I do not want to understand it, my work is something completely different.
Title: Re: is there an internet connection?
Post by: KodeZwerg on February 03, 2023, 03:27:21 pm
The problem is: I do not understand the details.
What you not understand, do it like link provided and you have a proper response.
I do not want to understand it
That is the worst a programmer can say, Pascal ain't a script language where you just copy/paste.
Title: Re: is there an internet connection?
Post by: JanRoza on February 03, 2023, 04:06:01 pm
What an answer!
If you don’t want to understand then why program at all?
Title: Re: is there an internet connection?
Post by: Bogen85 on February 03, 2023, 04:16:17 pm
Pascal ain't a script language where you just copy/paste.

 :D Haha!

Even in scripting languages blind copypasta without understanding what the copypasta is and does is a recipe for disaster! :D
Title: Re: is there an internet connection?
Post by: Bogen85 on February 03, 2023, 05:16:13 pm
The only thing I need, is a result only true, if there is a connection.

"Is there a connection" is a very broad and nebulous term.

My computer could have access to thousands of computer and websites, and not one of those be on the Internet.

A connection to what? Yes, I get it, the Internet...

But it is not simple check. Yes, high level tools do give you a simple status, because they are checking the ability to access to access some specific resource (or at least one of multiple resources) that can only be found on the Internet.

Hence what is discussed in the given topic/thread: https://forum.lazarus.freepascal.org/index.php/topic,43819.0.html

Title: Re: is there an internet connection?
Post by: Bogen85 on February 03, 2023, 05:21:34 pm
Do you think, you can just copy me the correct line form there?
The only thing I need, is a result only true, if there is a connection.

You might think it is simple, it is not.
Hence you need to understand it.

Checking for "an Internet connection" is complex. So you need to have some understanding of what is being checked for.
Title: Re: is there an internet connection?
Post by: Curt Carpenter on February 03, 2023, 06:48:24 pm
I think you just want to see if you can contact other computers that are connected to the internet.  If that's correct and you're using Windows, the easiest way to do this is to "ping" another computer that you know is in fact connected.  A way to do that is illustrated in this thread:

https://forum.lazarus.freepascal.org/index.php?topic=39409.0 (https://forum.lazarus.freepascal.org/index.php?topic=39409.0)

(Hope it helps.  You can make a career out of learning the ins and outs of the internet, so cut-and-paste is OK, IMHO, if you don't want to  :) )

Title: Re: is there an internet connection?
Post by: af0815 on February 03, 2023, 07:08:48 pm
If you have WIndows and block in a external firewall one server, your PC will always say "No Internet".

So you can only say, you have a connection to a server in internet and this mean you have internet. You can start a request to google or your own homepage or a ping to a known server (as Curt say) or read a ntp for time,...

So its your choice to say: I have internet, because xxx work.
Title: Re: is there an internet connection?
Post by: Thaddy on February 03, 2023, 07:17:01 pm
"ping"
Pings are dropped by any sane servers.... Bad advice.
Title: Re: is there an internet connection?
Post by: af0815 on February 03, 2023, 07:18:26 pm
BTW: M$ marked the InternetGetConnectedState as "Using this API is not recommended"
Title: Re: is there an internet connection?
Post by: Bogen85 on February 03, 2023, 08:21:38 pm
So you can only say, you have a connection to a server in internet and this mean you have internet. You can start a request to google or your own homepage or a ping to a known server (as Curt say) or read a ntp for time,...

So its your choice to say: I have internet, because xxx work.

Agreed.

However....

What really matters is the Internet resources your app needs to connect to.

However...

So, what does it mean to have an "Internet connection"?

If I can't access DNS correctly but I can connect to sites by address, does that mean I have an "Internet connection"?
If I can use DNS and can access some sites, but not the one I'm checking on or need, does that mean I do not have an "Internet connection"?

True, OP Nicole does not need to know all that is involved or have a deep understanding of DNS, routers, firewalls, gateways, NAT, VPN, proxies, etc...

But OP Nicole needs to establish what an "Internet connection" means for said application, and go from there...
Title: Re: is there an internet connection?
Post by: Nicole on February 04, 2023, 10:50:47 am
ok, then I put it differently:

When anything goes wrong with the internet, I do something what I do not understand neither, but does the job in absolute every of my needs since many years without exception.

(windows)
Win-key + r
cmd
ping 4.2.2.1
(no idea who is this server and I do not care)

The man that days says, this "checks for the internet".
And it does.
Either I see the ping result in milliseconds or a "timeout".

This job I want my software doing - instead of my fingers in the command-shell.
Need not be the command shell, can be every kind of line or ping.
Best of all it would be my ping above.

Unfortunately I do not know, how to send a ping by Lazarus and how to grab its results.

Title: Re: is there an internet connection?
Post by: dseligo on February 04, 2023, 11:43:49 am
Unfortunately I do not know, how to send a ping by Lazarus and how to grab its results.

Curt Carpenter in post #9 already gave you a link.
Title: Re: is there an internet connection?
Post by: paweld on February 04, 2023, 12:02:36 pm
You can use the Indy package
Title: Re: is there an internet connection?
Post by: af0815 on February 04, 2023, 12:22:59 pm
It is possible to make it with synapse (from OPM), i use it under win, linux, linux-arm,...

Code: Pascal  [Select][+][-]
  1. uses
  2.   pingsend;
  3.  
  4. const
  5.   MaxPingCnt = 5;
  6.  
  7. procedure PingServerSilent(const HostIP: String; var IsOk: Boolean);
  8. var
  9.   cnt: Integer;
  10.   aPing: TPINGSend;
  11. begin
  12.   aPing:= TPINGSend.Create;
  13.   try
  14.     aPing.Timeout:=500;
  15.     cnt := MaxPingCnt;
  16.     aPing.Sock.SocksTimeout:= 500;
  17.     while not aPing.Ping(HostIP) and (cnt > 0) do begin
  18.       dec(cnt);
  19.       sleep(10);
  20.     end;
  21.     IsOk := (cnt > 0);
  22.   finally
  23.     aPing.Free;
  24.   end;
  25. end;
  26.  
Title: Re: is there an internet connection?
Post by: Thaddy on February 04, 2023, 12:50:29 pm
Please do stop with advising ping as a reliable solution. Really, most servers drop ping requests.
Simply try to connect to example.com which is IANA itself.
Title: Re: is there an internet connection?
Post by: Bogen85 on February 04, 2023, 03:37:30 pm
Please do stop with advising ping as a reliable solution. Really, most servers drop ping requests.
Simply try to connect to example.com which is IANA itself.

Yes!  ;D

Also if only http/https connections are being made, they might be using a proxy, and there might not be any actual Internet route (in which case no pings would work at all, even for servers on the Internet that reply to ping requests).
Title: Re: is there an internet connection?
Post by: Curt Carpenter on February 04, 2023, 05:38:57 pm
The "anti-pingites" raise an interesting question:  how would one go about finding out a rough measure of the number of the world's servers that refuse pings?  And if it is a regional thing?  Same for ntp. Is it a big number?  I have no idea.

If nothing else, you can ping your own router, if there is one -- and that may or may not answer Nicole's question.  It would at least offer a clue as to the probability of an internet connection.

I've been hacking away on the net since the 90s and Mosaic and have never had a problem finding something ping-able or ntp-able -- but all in the U.S..   Ping floods are so '90s anymore anyway that the security achieved by disallowing pings and ntps is hardly worth it:  if your server is blocking them, ask them to stop!
Title: Re: is there an internet connection?
Post by: Bogen85 on February 04, 2023, 05:54:06 pm
The "anti-pingites" raise an interesting question:  how would one go about finding out a rough measure of the number of the world's servers that refuse pings?  And if it is a regional thing?  Same for ntp. Is it a big number?  I have no idea.

I not completely an "anti-pingite"... I of course use it when troubleshooting connections.
I just don't use it for generalize automated checks to see if I have a connection (I do it use it for checking my own remote servers in specialized checks).

I've also worked at places (1990s, 2000s, 2010s, even 2020s) that were proxy only for all outgoing Internet connections, so there was not way to ping servers outside the company network. (and of course worked at places where the outside servers could be pinged).
Title: Re: is there an internet connection?
Post by: Bogen85 on February 04, 2023, 06:03:05 pm
There are a variety of "what is my IP address" sites...

Having a check that uses a list of those and returns TRUE on first successful transaction, and FALSE on not being able to complete a transaction with any of them could be a good general approach for checking for an Internet connection...

It would be checking a variety of things (DNS, access to external sites, etc) needed to make outgoing connections.
Title: Re: is there an internet connection?
Post by: loaded on February 04, 2023, 06:08:32 pm
Google's famous server 8.8.8.8 always responds to ping requests 24/7.
Title: Re: is there an internet connection?
Post by: 440bx on February 04, 2023, 07:22:00 pm
There is an inherent problem in determining the existence of an internet connection. 

The problem is, its existence is not guaranteed in any way.   If there is/was a connection, it can "vanish" at any time before it is used.


Title: Re: is there an internet connection?
Post by: dseligo on February 04, 2023, 07:37:53 pm
Google's famous server 8.8.8.8 always responds to ping requests 24/7.

And so is 8.8.4.4. I use these because they are easy to remember and when you are having DNS problems, ping those two can reveal that in seconds.
I don't know why ping is so frown on.
Title: Re: is there an internet connection?
Post by: af0815 on February 04, 2023, 07:48:36 pm
Thaddy says it not a so good idea to use ping for this. Yes, a lot of companies block ping for a good reason.

A defined request to a known site with https is a good soloution, M$ itself use such a request for checking the connection. But if you have no server for this of your own, you must use the "poor man" version with ping. (or try to reach google,...) 
Title: Re: is there an internet connection?
Post by: Bogen85 on February 04, 2023, 07:50:57 pm
I don't know why ping is so frown on.

Because they are not a comprehensive solution for an Internet resource access check...
Ability to access resources on the Internet often does not rely on routed access for every protocol to those resources.
Yes, for many (most?) home users, hotel/airport Internet users, workplace place internet users, that is the case... (routed access works).

But not always for every protocol in every setup...

I'm not going to force my home access to not be fully routed (it is through NAT though), but I can't guarantee that everywhere else I use the Internet that pings will work, as experience travelling and at some places I've worked at, pings don't work.
Rare that they don't, but I don't consider the places they don't work as one off oddball situations.

As such, I won't ever recommend pinging as a general method for an automated internet resource access check.
Specific to certain use cases, sure, but not as general reliable access check method.
Title: Re: is there an internet connection?
Post by: Curt Carpenter on February 04, 2023, 07:52:48 pm
Quote
The problem is, its existence is not guaranteed in any way. 

The problem is, to paraphrase Lewis Carroll, that existence in general is not guaranteed in any way :)
Title: Re: is there an internet connection?
Post by: 440bx on February 04, 2023, 09:25:16 pm
The problem is, to paraphrase Lewis Carroll, that existence in general is not guaranteed in any way :)
Indeed the existence problem is not specific to the internet (unfortunately ;) )
Title: Re: is there an internet connection?
Post by: dbannon on February 04, 2023, 11:51:49 pm
I have to say that pinging google is a pretty reliable solution.

Many systems stopped responding to the "mandatory ECHO_REQUEST" (to quote my man page) when the Ping of Death became a big thing. Since then the internet has learnt to deal with a lot more elaborate DOS attacks and just pinging someone does not really cut it. So, again, a good number of systems do support ping again.

From memory, and I cannot find a reference, google did announce that they intended to always respond to ping except in exceptional, short term circumstances. (It may have been at a conference ?)

I always ping google.com, that way, as well as connectivity, I ensure I also have DNS.

So, yes, there is theoretical argument that maybe the net is OK but someone has accidentally knocked the power lead out of the googles server but I think you are pretty safe.  I'm more worried about cosmic radiation flipping ram bits than google being offline.

Davo
Title: Re: is there an internet connection?
Post by: Nicole on February 08, 2023, 07:18:11 pm
Paweld, thanks for the project.
Unfortunately I have huge problems with it (Laz. 2.2.4).

The IDE shutw down or gives me error-messages on displaying the form by F12 after a few seconds.
Another attempt made Lazarus "just disappear".

Let me put it like this.
Can somebody help me to write such a method

function myPing: Boolean;

begin
  result:=false;

  ping 4.2.2.1;  // no idea, how to send
  GetAnswertime;  // no idea, how I can get it
  If answertime > 0 and answertime < 300  // or a similar check for "there is some internet"
    then result:=true;

end;
 
Title: Re: is there an internet connection?
Post by: JanRoza on February 08, 2023, 07:51:50 pm
Quote
ping 4.2.2.1;  // no idea, how to send 

Of course you know how, AF0815 already gave you an answer with code in which you can see how to ping.
What’s the use of examples if you don’t study them?
Title: Re: is there an internet connection?
Post by: af0815 on February 08, 2023, 07:54:12 pm
and you have two timeouts in the sample. With this you can deal with the answertime. Your version of Lazarus is meaningless, the sample works for years and on win32, win64, linux-x64, linux-arm,...
Title: Re: is there an internet connection?
Post by: Curt Carpenter on February 08, 2023, 09:30:28 pm
You will conquer it Nicole!

Can you use the Online Package Manager to install the Synapse 40.1 package on your computer? 
Title: Re: is there an internet connection?
Post by: KodeZwerg on February 08, 2023, 10:20:24 pm
To me, the only reliable way is to send or get real data.
Do it like Microsoft do it since ages.
I already read, you do not want to learn how things are working, you just want to copy and paste something what others made.
So here copy this and place it in a unit which uses WinINet.
Code: Pascal  [Select][+][-]
  1. function CheckMicrosoftConnectivity(const SuppressErrors: Boolean = False): Boolean;
  2. var
  3.   NetHandle: HINTERNET;
  4.   UrlHandle: HINTERNET;
  5.   Buffer: array[0..1023] of Byte;
  6.   BytesRead: DWord;
  7.   StrBuffer: UTF8String;
  8.   Received: string;
  9. begin
  10.   Result := False;
  11.   Received := '';
  12.   StrBuffer := '';
  13.   BytesRead := Default(DWord);
  14.   NetHandle := InternetOpen('Mozilla/5.0(compatible; WinInet)', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  15.   if Assigned(NetHandle) then
  16.     try
  17.       UrlHandle := InternetOpenUrl(NetHandle, PChar('http://www.msftncsi.com/ncsi.txt'), nil, 0, INTERNET_FLAG_RELOAD, 0);
  18.       if Assigned(UrlHandle) then
  19.         try
  20.           repeat
  21.             if InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead) then
  22.               SetString(StrBuffer, PAnsiChar(@Buffer[0]), BytesRead);
  23.             Received := Received + StrBuffer;
  24.           until BytesRead = 0;
  25.           Result := (Received = 'Microsoft NCSI');
  26.         finally
  27.           InternetCloseHandle(UrlHandle);
  28.         end
  29.       else
  30.         if not SuppressErrors then
  31.           ShowMessage('Cannot open URL: www.msftncsi.com');
  32.     finally
  33.       InternetCloseHandle(NetHandle);
  34.     end
  35.   else
  36.     if not SuppressErrors then
  37.       ShowMessage('Unable to initialize WinInet');
  38. end;
It does not require any kind of SSL library.

If you find it useful and want to learn, Microsoft has all the answers.
Title: Re: is there an internet connection?
Post by: Joanna on February 09, 2023, 02:28:00 am
Here is a way to detect internet connection given to me awhile ago by someone in IRC.

uses pingsend file of laz_synapse unit

myPINGSEND:TPINGSend; 

FUNCTION CAN_CONNECT( CONST URL: STRING) : BOOLEAN;
 BEGIN
 try
    RESULT:= myPingSend.Ping(URL);
   finally
   end;
 END;

I_have_internet:= CAN_CONNECT('1.1.1.1');
Title: Re: is there an internet connection?
Post by: Nicole on February 15, 2023, 10:16:03 am
@KodeZwerg
Finally the output window is solved, did not expect it to take that long.
Next task: ping, thank you so much for the demo.

This is my problem
IdIcmpClient
of the uses list is not found.

What to change?
Title: Re: is there an internet connection?
Post by: KodeZwerg on February 15, 2023, 10:46:26 am
What to change?
With my demo you do not need Ping or Indy or Ssl or admin rights to execute or whatever else bad reasons exists to not use Ping.
You only need to include WinINet, that is already a basic unit when you install Lazarus, and get a result of my method, so I do not really understand your question at all.

I am happy that you fixed some of the problems you are into.
Title: Re: is there an internet connection?
Post by: TRon on February 15, 2023, 11:13:05 am
@KodeZwerg:
I believe the remark you quoted from TS was addressed at the wrong person, hence your confusion ?

It seems to me the project from paweld in post #16 (https://forum.lazarus.freepascal.org/index.php/topic,62144.msg469793.html#msg469793) uses indy.

@Nicole:
If you are indeed referring to paweld's project then you need to install the Indy components to solve the compiler error. It can't find the unit because you do not seem to have indy installed.

Unfortunately I can't give advise on how to install indy as the last time I tried to do that in Lazarus (Linux) it failed for me.
Title: Re: is there an internet connection?
Post by: KodeZwerg on February 15, 2023, 11:38:18 am
@KodeZwerg:
I believe the remark you quoted from TS was addressed at the wrong person, hence your confusion ?

It seems to me the project from paweld in post #16 (https://forum.lazarus.freepascal.org/index.php/topic,62144.msg469793.html#msg469793) uses indy.
That makes sense  :D

Okey, rewind, download this file: NicolesProject.zip (https://forum.lazarus.freepascal.org/index.php/topic,62232.msg470579.html#msg470579)
Extract its content into a new folder of your choice.
Open Lazarus and click on open project.
Change filter from *.lpi to *.* and select project1.lpr file, when asked to create a new project for it, say yes and choose application (lcl).
Click now the menu project options and choose project inspector.
Now click on the small down arrow at the "Add" and choose "New Requirement" (Image 1)
Select Indy (Image 2) and press "OK"
Now you can close the Project Inspector and project will compile.

If you not have Indy installed, you can do it with the OPM utility very easy (Image 3)

Are questions left?

Title: Re: is there an internet connection?
Post by: marcov on February 15, 2023, 11:40:20 am
Kodezwerg: It might we worthwhile to arrange that example to fit into winutils (an unit for small winapi calls).  Do you know if this can fail in case of proxy misconfiguration?

icmp direct use afaik indeed requires admin rights.
Title: Re: is there an internet connection?
Post by: KodeZwerg on February 15, 2023, 11:51:17 am
Do you know if this can fail in case of proxy misconfiguration?
I do use InternetOpen (https://learn.microsoft.com/en-us/windows/win32/api/wininet/nf-wininet-internetopenw) with INTERNET_OPEN_TYPE_PRECONFIG flag.
Quote
Retrieves the proxy or direct configuration from the registry.
I guess when your computer has a corrupt configuration that it fail but I never tested it under such condition (!!)
I am sorry that I neither can say clearly yes or no.
Title: Re: is there an internet connection?
Post by: Nicole on February 15, 2023, 09:11:56 pm
@KodeZwerg: Thank you for your patience.
I implemented your function now and for the first time the job is done without problems, without error-message, without strange unit.

Now, you will ask: "Why did she hesitate to do so for one moment?"

Well, there are reasons, 2 of them:

1)
Once upon a time there was a rainy day, I did nothing special at all, nothing with the net, nothing with software, no browser, really nothing.
On this day my DNS-resolving was shot. It took me a while to find out about my connection problem at all.
My Win 7 ate my DNS-resolutioin. Somehow I repaired them. Long ago, I cannot remember any more how. My backup shall hold a file about.

To sum up: I rather would prefer a check without DNS-resolve needed.

2)
It is Microsoft. Those hated-by-me-guys have the best operating system and I use the stuff of them all they long, because it is grrr good. Never the less, I would prefer a solution without them. One day I will work on without them, yes. LibreOffice shelters me since long and the operating system will follow.

Here is a list of servers I would prefer to contact, but I do not know how. http://4.2.2.1 does not work.
https://sebastianhetzel.net/zuverlaessige-oeffentliche-dns-server/
Title: Re: is there an internet connection?
Post by: Bogen85 on February 15, 2023, 09:52:23 pm
Here is a list of servers I would prefer to contact, but I do not know how. http://4.2.2.1 does not work.

Because it is for DNS protocol, not HTT Protocol.

https://sebastianhetzel.net/zuverlaessige-oeffentliche-dns-server/

For each of the addresses you need to know the protocol needed to connect to them.
(Or what protocols they understand and respond to)

Looking at that page, all appear to be DNS, so you would need to issue DNS queries using them

But... you might ask, why would DNS be suggested, when DNS is not wanted to be relied on.

Because DNS queries do not require your DNS setup to be working...

4.2.2.1 does respond to ping though (the ICM Protocol).
Title: Re: is there an internet connection?
Post by: Bogen85 on February 16, 2023, 06:39:20 am
Here is a list of servers I would prefer to contact, but I do not know how. http://4.2.2.1 does not work.
https://sebastianhetzel.net/zuverlaessige-oeffentliche-dns-server/

As I said before, those are DNS servers.
However, they seem to be either https://www.rfc-editor.org/rfc/rfc5966 or https://www.rfc-editor.org/rfc/rfc7766 compliant, as they are accepting TCP connections on port 53.

If you don't care if they are working or not, but that you are merely able to connect to at least one, something like the following should work:

Code: Pascal  [Select][+][-]
  1. program checkdns_ex;
  2.  
  3. {$mode objfpc}
  4. {$H+}
  5.  
  6. uses
  7.   baseunix, // needed for TTimeVal (what about windows?)
  8.   Sockets,
  9.   types;
  10.  
  11. function checkConnect (const hostAddress: string; portNumber: integer; timeout: integer = 3): Boolean;
  12.   var
  13.     sock:    LongInt;
  14.     addr:    TSockAddr;
  15.     timeset: TTimeVal; // is TTimeVal available on windows?
  16.   begin
  17.     sock := fpsocket(AF_INET, SOCK_STREAM, 0);
  18.     if sock = -1 then begin
  19.       result := false;
  20.       Exit;
  21.     end;
  22.  
  23.     timeset.tv_sec  := timeout;
  24.     timeset.tv_usec := 0;
  25.     fpsetsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, @timeset, SizeOf(timeset));
  26.  
  27.     addr.sin_family := AF_INET;
  28.     addr.sin_port   := htons(portNumber);
  29.     addr.sin_addr   := StrToNetAddr(hostAddress);
  30.  
  31.     result := 0 = fpconnect(sock, @addr, SizeOf(addr));
  32.  
  33.     CloseSocket(Sock);
  34.   end;
  35.  
  36. function checkAnyConnect (const hosts: TStringDynArray; const port: integer = 53): boolean;
  37.   var
  38.     host: string;
  39.   begin
  40.     for host in hosts do if checkConnect(host, port) then exit(true);
  41.     result := false;
  42.   end;
  43.  
  44. begin
  45.   if checkAnyConnect([
  46.     '4.2.2.1',
  47.     '4.2.2.2',
  48.     '4.2.2.3',
  49.     '4.2.2.4',
  50.     '4.2.2.5',
  51.     '4.2.2.6']) then writeln('Connection Success')
  52.   else
  53.     writeln('Connection Failed');
  54. end.

I don't have any Windows setup to test on, I tested on Linux. I'm not sure on Windows, I had to use baseunix for the TTimeVal type definition to set a decent connection timeout.
Title: Re: is there an internet connection?
Post by: Bogen85 on February 16, 2023, 06:47:25 am
I don't have any Windows setup to test on, I tested on Linux. I'm not sure on Windows, I had to use baseunix for the TTimeVal type definition to set a decent connection timeout.

On Windows it is likely winsock or winsock2 that is needed for TTimeVal.
Title: Re: is there an internet connection?
Post by: balazsszekely on February 16, 2023, 07:50:18 am
I don't have any Windows setup to test on, I tested on Linux. I'm not sure on Windows, I had to use baseunix for the TTimeVal type definition to set a decent connection timeout.

On Windows it is likely winsock or winsock2 that is needed for TTimeVal.
With a small modification your code works on windows too. Here is a cross platform version, tested on Win10/Linux Mint 20.02, both 64 bit:
Code: Pascal  [Select][+][-]
  1. program checkdns_ex;
  2.  
  3. {$mode objfpc}
  4. {$H+}
  5.  
  6. uses
  7.   Classes, Sysutils, Sockets, Types,
  8.   {$IFDEF WINDOWS}
  9.   Windows,
  10.   Winsock;
  11.   {$ELSE}
  12.   BaseUnix,
  13.   UnixType;
  14.   {$ENDIF}
  15.  
  16. function checkConnect (const hostAddress: string; portNumber: integer; timeout: integer = 3): Boolean;
  17. var
  18.   sock:    LongInt;
  19.   addr:    TSockAddr;
  20.   timeset: TTimeVal; // is TTimeVal available on windows?
  21. begin
  22.   sock := fpsocket(AF_INET, SOCK_STREAM, 0);
  23.   if sock = -1 then begin
  24.     result := false;
  25.     Exit;
  26.   end;
  27.  
  28.   timeset.tv_sec  := timeout;
  29.   timeset.tv_usec := 0;
  30.   fpsetsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, @timeset, SizeOf(timeset));
  31.  
  32.   addr.sin_family := AF_INET;
  33.   addr.sin_port   := htons(portNumber);
  34.   addr.sin_addr   := TInAddr(StrToNetAddr(hostAddress));
  35.  
  36.   result := 0 = fpconnect(sock, @addr, SizeOf(addr));
  37.  
  38.   CloseSocket(Sock);
  39. end;
  40.  
  41. function checkAnyConnect (const hosts: TStringDynArray; const port: integer = 53): boolean;
  42. var
  43.   host: string;
  44. begin
  45.   for host in hosts do if checkConnect(host, port) then exit(true);
  46.   result := false;
  47. end;
  48.  
  49. begin
  50.   if checkAnyConnect([
  51.     '4.2.2.1',
  52.     '4.2.2.2',
  53.     '4.2.2.3',
  54.     '4.2.2.4',
  55.     '4.2.2.5',
  56.     '4.2.2.6']) then writeln('Connection Success')
  57.   else
  58.     writeln('Connection Failed');
  59. end.
TinyPortal © 2005-2018