How to check if you have live internet connection programmatically using C++ - c++

How can I check if I have a internet connection or live internet connection using C++?

C++ has no builtin functions for this, you will need to resort to system APIs. An easiest and obvious way is to create a socket and try to connect it to some known IP or check if DNS is working.
Some useful links:
http://msdn.microsoft.com/en-us/library/ms740673(VS.85).aspx (Windows Sockets)
http://www.tenouk.com/cnlinuxsockettutorials.html (Linux/Unix sockets)

The easiest way is to try to connect to a known outside IP address. If it fails in Windows, the connect function will return SOCKET_ERROR, and WSAGetLastError will usually return WSAEHOSTUNREACH (meaning the packet couldn't be sent to the host). In Linux, you'll get back a -1, and errno will be ENETUNREACH.

For starters you can subscribe to the ISensIntf to check if you have a valid network connection. (Let me know if you need help in this. Its painful to register for the events etc.).
After that, you can use Api's like IsNetworkAlive, InternetGetConnectedStateEx or the InternetCheckConnection to check connectivity to the internet etc.
If your using C# or VB, then first Add a reference to
Microsoft.VisualBasic.Code.
Microsoft.VisualBasic.Devices.Network network = new Microsoft.VisualBasic.Devices.Network();
network.NetworkAvailabilityChanged += new Microsoft.VisualBasic.Devices.NetworkAvailableEventHandler(network_NetworkAvailabilityChanged);
...
private static void network_NetworkAvailabilityChanged(object sender, Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs e)
{
if (e.IsNetworkAvailable)
{
//network is connected.. do something..
}
else
{
//network isnt connected.. do something else.
}
Hope this helps

Related

How to get your public ip address using Qt c++

I'm writing a gui for an net address etc. calculator. All the coding is done but now i want to have a button that will get your computer's ip address. I was looking for a solution and saw various posts on stackoverflow but none of them work for me...
Edit: this piece of code worked for me
QTcpSocket socket;
socket.connectToHost("8.8.8.8", 53);
if (socket.waitForConnected()) {
QString text = socket.localAddress().toString();
ui->ipAddress->setText(text);
} else {
QMessageBox msg;
msg.setText("Couldn't connect to the DNS server! No internet connection...");
msg.setWindowTitle("No internet connection");
msg.setIcon(QMessageBox::Critical);
msg.exec();
}```
I think the class you are looking for is the QNetworkInterface class.
From the man page:
The QNetworkInterface class provides a listing of the host's IP
addresses and network interfaces.
For example, calling QNetworkInterface::allAddresses() is a quick way to get a list of all the IP addresses on your machine. As for which one is the "public IP address", that's not a well-defined concept. On most modern consumer setups, it's arguable that there is no public IP address, as consumer PCs are typically hidden behind a NAT layer, and as such the only public IP address is on the network router, not on the user's computer itself.
You can use QHostInfo for this purpose. Ex;
auto list = QHostInfo::fromName(QHostInfo::localHostName()).addresses();
I am using following code snippet in my current project to get ip address. And it is working fine both on Desktop Linux and Embedded Linux. device is network interface name like "wlan0", "eth0" etc. It returns QNetworkAddressEntry which contains both ip and netmask. Use ip() function get ip address. Usually the first address entry is non-virtual one, so that's why am getting the first one.
const QNetworkInterface& networkInterface = QNetworkInterface::interfaceFromName(device);
if (networkInterface.isValid())
{
const QList<QNetworkAddressEntry>& addressEntries = networkInterface.addressEntries();
if (!addressEntries.isEmpty())
return addressEntries.front();
}
return QNetworkAddressEntry(); // could not found, invalid adress entry
Don't forget to add QT += network to your pro file.
Using QNetworkAccessManager, you can tap this free REST api: https://www.ipify.org/
That supports various options, such as returning the results in json. If you simply get that url, it will respond with the ip address you are most likely hoping to get back, in a raw format (i.e. a naked string).

WebSocket is closed before the connection is established [duplicate]

I'm using JavaScript and the Union platform How would I go about diagnosing this problem? Many thanks.
If you go to http://jsbin.com/ekusep/6/edit and view the JavaScript console you'll see the 'WebSocket is closed before the connection is established' logged. I've tested this in Chrome.
In this code what it means is that ws.close() was called (by user code) before the connection was even given a chance to be established.
So, the cause of this error is if code attempts to close the WebSocket connection before it's had a chance to actually connect.
In React you need to add this to your useEffect in return
useEffect(() => {
socket = new WebSocket(address);
return () => {
if (socket.readyState === 1) { // <-- This is important
socket.close();
}
};
For anybody else coming in to find an answer, apart from what #leggetter has mentioned above, in my case, it turned out that I was missing the port number while establishing a connection. I was using socket.io if that helps.
http://websocket.service:8000
Just open the port in server
ufw enable

Managing a global DB connection in C++

Is is possible to do the following safely:
I have a C++ library which connects to SQL DB at various points. I would like to have a global connection available at all of these points. Can this be done? IS there a standard pattern for this. I was thinking of storing a connection in a singleton.
Edit:
Suppose I have the following interface for the connection.
class Connection {
public:
Connection();
~Connection();
bool isOpen();
void open();
}
I would like to implement the following interface:
class GlobalConnection {
public:
static Connection & getConnection() {
static Connection conn_;
if (!conn_.isOpen())
conn_.open();
return conn_;
}
private:
GlobalConnection() {};
Connection conn_;
};
I have two concerns with the above. One is that the getConnection is not thread safe and the other is that I'm not sure about the destruction of the static resource. In other words, am I guaranteed that the connection will close (ie its destructor will be called).
For the record, the connection class itself is provided by the SQLAPI++ library (though that's not very relevant).
EDIT 2: After doing some research it seems that while SQLAPI doent directly support pooling it can be used to enable connection pooling through the ODBC facilities via the call
setOption("SQL_ATTR_CONNECTION_POOLING") = SQL_CP_ONE_PER_DRIVER
The documentation says that that this call must be made before the first connection is established. What is the best way to assure this in code with multiple potential call sites for opening a connection. What if this doesn't happen? Will an error be thrown or pooling just wont be enabled.
Also what tools are available for monitoring how many open connections there are to the DB?
A Singleton can solve this in any OO language. In C/C++, you can also use a static variable (in case you don't use a pure-OO coding style).
most client libaries support connection pooling.
so open a new connection will just pick a existing connection from the pool.

disconnecting from mongoDb with C++ driver

i'm sure this must be really simple or i'm missing the point, but how do you disconnect from Mongo using the C++ driver and DBClientConnection? DBClient has a public member of 'connect' but no disconnect/kill/drop etc that I can find.
There is some talk (in stack overflow and on the web) of using ScopedDBConnection which does seem to be able to allow me to drop my connection - but there are very few examples of how it would be used - or info on when I should use that class over the DBClientConnection class.
Any ideas?
If you're using a DBClientConnection, it has one connection, and you aren't supposed to disconnect/reconnect. I guess it kills the connection when it calls the destructors. You can set it up to automatically reconnect so you can keep using it if it loses its connection.
If you want to have connection pooling and multiple connections, you want to use ScopedDBConnection. You can see some examples here: https://github.com/mongodb/mongo/blob/master/src/mongo/client/model.cpp
Here's the gist:
ScopedDbConnection conn("localhost");
mongo::BSONObjBuilder obj;
obj.append( "name" , "asd" );
conn->insert("test.test", obj);
conn.done();
Basically, you can do anything with conn that you can do with a DBClientConnection, but when you're done you call done().

Simple C/C++ network I/O library

I have the following problem to solve. I want to make a number of requests to a number of "remote" servers (actually, a server farm we control). The connection is very simple. Send a line, and then read lines back. Because of the number of requests and the number of servers, I use pthreads, one for each request.
The naive approach, using blocking sockets, does not work; very occasionally, I'll have a thread stuck in 'connect'. I cannot use SIGALRM because I am using pthreads. I tried converting the code to O_NONBLOCK but this vastly complicated the code to read single lines.
What are my options? I'm looking for the simplest solution that allows the following pseudocode:
// Inside a pthread
try {
req = connect(host, port);
req.writeln("request command");
while (line = req.readline()) {
// Process line
}
} catch TimeoutError {
// Bitch and complain
}
My code is in C++ and I'm using Boost. A quick look at Boost ASIO shows me that it probably isn't the correct approach, but I could be wrong. ACE is far, far too heavy-weight to solve this problem.
Have you looked at libevent?
http://www.monkey.org/~provos/libevent/
It's totally different paradigm but the performance is so amazing.
memcached is built on top of libevent.
I saw the comments and i think you can use boost::asio with boost::asio::deadline_timer
Fragment of a code:
void restart_timer()
{
timer_.cancel();
timer_.expires_from_now(boost::posix_time::seconds(5));
timer_.async_wait(boost::bind(&handleTimeout,
MyClass::shared_from_this(), boost::asio::placeholders::error));
}
Where handleTimeout is a callback function, timer_ is boost::asio::deadline_timer
and MyClass is similar to
class Y: public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
You can call restart_timer before connect ou read/write
More information about share_from_this()
You mentioned this happens 'very occasionally'. Your 'connect' side should have the fault tolerance and error handling you are looking for but you should also consider the stability of your servers, DNS, network connections, etc.
The underlying protocols are very sturdy and work very well, so if you are experiencing these kind of problems that often then it might be worth checking.
You may also be able close the socket from the other thread. That should cause the connect to fail.