is there any way to check internet connection status in linux using mono
If it's desktop app, you could query NetworkManager (which is the network connection manager on most Linux desktops) over d-bus, using the NDesk.DBus library.
See Banshee for an example: http://git.gnome.org/cgit/banshee/tree/src/Core/Banshee.Services/Banshee.Networking/NetworkManager.cs
Apart from what Michael already suggested for a desktop application, you can also do something like:
foreach (NetworkInterface ni in NetworkInformation.GetAllNetworkInterfaces ()) {
// Check that any or all of:
// -ni.OperationalStatus == OperationalStatus.Up
// -that ni.NetworkInterfaceType is ethernet or wireless80211
// -ni.GetIPProperties() has a gateway and a DNS server
// ...
}
No matter what you end up using, it won't be reliable.
I see it all the time with Windows Vista and 7 at home. I use a home network, so my computers are always "connected." However, they are not always connected to the Internet.
That said, I would recommend checking the network interfaces as Gonzalo said. It is your best bet.
I would not rely on NetworkManager being present. I hate that thing and turn it off whenever I can. It is huge, ungainly, has an ugly name, relies on junk like HAL and DBUS. Early versions permanently put me off because they didn't work unless you were logged in to a GUI. It also collected bug work-arounds for wifi that were completely ridiculous in an open-source operating system that should have just fixed the original bugs. That led to other wifi managers and the command-line not being able to work properly and people being told to use NetworkManager, only because no one ever bothered to fix the actual bug!
You could try to open your connection as it is needed. If that fails display an error message.
Alternatively, if you really need a general check (e.g. at application start) you could try to make HTTP requests to one or more omnipresent websites like google.com. (Or what ever protocol you mean by "internet").
Check out HttpWebRequest.
Related
Introduction
I have a Windows Phone 8.1 Silverlight (WP8.1 SL) based app in the store. Some users complain about performance issues when they have a bad network connection. I searched a bit and came up with the idea that it might be related to new LicenseInformation() that gives me the information of whether the app is running in Trial mode or not. The question is, whether this requires network information or not, and whether CurrentApp.LicenseInformation is a suitable replacement for a WP8.1 SL app.
Background and What I did so far
In general, the app does not need a network connection (no data to load, no advertisements, ...). To confirm that I used Fiddler to watch over the network sent by my phone. The result was that no network traffic is generated. However, the problem still persists.
After a lot of research and playing around I got the feeling that this issue might be related to the code part that checks on whether the app is in trial mode or not. I use the following code to check that.
var li = new LicenseInformation();
if (li.IsTrial()) {
...
}
I do this a couple of times during startup. So in case IsTrial() requires a network connection this could be the actual issue when there is only a bad connection available. But again, I couldn't find anything using Fiddler. The documentation (see here) for LicenseInformation does not mention whether a network connection is required or not.
Searching around I found that there is an updated interface available for both WP 8.1 SL and also W10M UWP.
var li = CurrentApp.LicenseInformation;
if (li.IsTrial) {
...
}
Its documentation clearly states that there is no network connection required for that (see here).
Even though the docs say that CurrentApp.LicenseInformation is also available on WP8 I also found some references that say that you only get a reliable answer for the IsTrial-question when using new LicenseInformation() (e.g. here).
Actual Questions
Is new LicenseInformation() required on WP8.1 SL, or can I use CurrentApp.LicenseInformation as well?
Does new LicenseInformation() require a network connection compared to CurrentApp.LicenseInformation?
I have a component that (by part) uses an internet connection. I wrote some UnitTests to ensure that to component is working. However, I would like to test the behaviour of the component without internet connections.
So, my goal is to somehow temporary disable internet, or the whole internet connection, and reactivate after test.
I would disable\enable like here local are connection in test initialization
[ClassInitialize]
SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
if (((string)item["NetConnectionId"]) == "Local Network Connection")
{
item.InvokeMethod("Disable", null);
}
}
[ClassCleanup()]
// Enable local area connetcion
There are many ways in which the system could have "No Internet" and the answer really depends on what you mean.
As the accepted other answer suggests, you could simply disable the network interface. That guarantees you have no internet, but the computer also will know it has no network either.
A couple other options are
To remove your Default Gateway (this may require setting static IP settings in the control panel, though I'm sure you could do it programmatically as well)
This way, the computer still thinks it's connected, but it won't have any network access except on the local subnet
Remove DNS server settings, see above link.
This way, the computer has direct IP based access but to a regular user it would appear as if there was "no internet."
Whilst not a direct answer to your question I believe you may find some use in this tool - https://jagt.github.io/clumsy/download
I've used it at work to simulate different network conditions for an mobile app that I'm currently working on. It is possible to completely disable the network connection by setting packet drop to 100%.
We are currently working on an API for an existing system.
It basically wraps some web-requests as an easy-to-use library that 3rd party companies should be able to use with our product.
As part of the API, there is an event mechanism where the server can call back to the client via a constantly-running socket connection.
To minimize load on the server, we want to only have one connection per computer. Currently there is a socket open per process, and that could eventually cause load problems if you had multiple applications using the API.
So my question is: if we want to deploy our API as a single standalone assembly, what is the best way to fix our problem?
A couple options we thought of:
Write an out of process COM object (don't know if that works in .Net)
Include a second exe file that would be required for events, it would have to single-instance itself, and open a named pipe or something to communicate through multiple processes
Extract this exe file from an embedded resource and execute it
None of those really seem ideal.
Any better ideas?
Do you mean something like Net.TCP port sharing?
You could fix the client-side port while opening your socket, say 45534. Since one port can be opened by only one process, only one process at a time would be able to open socket connection to the server.
Well, there are many ways to solve this as expressed in all the answers and comments, but may be the simpler way you can use is just have global status store in a place accesible for all the users of the current machine (may be you might have various users logged-in on the machine) where you store WHO has the right to have this open. Something like a "lock" as is used to be called. That store can be a field in a local or intranet database, a simple file, or whatever. That way you don't need to build or distribute extra binaries.
When a client connects to your server you create a new thread to handle him (not a process). You can store his IP address in a static dictionary (shared between all threads).
Something like:
static Dictionary<string, TcpClient> clients = new Dictionary<string, TcpClient>();
//This method is executed in a thread
void ProcessRequest(TcpClient client)
{
string ip = null;
//TODO: get client IP address
lock (clients)
{
...
if (clients.ContainsKey(ip))
{
//TODO: Deny connection
return;
}
else
{
clients.Add(ip, client);
}
}
//TODO: Answer the client
}
//TODO: Delete client from list on disconnection
The best solution we've come up with is to create a windows service that opens up a named pipe to manage multiple client processes through one socket connection to the server.
Then our API will be able to detect if the service is running/installed and fall back to creating it's own connection for the client otherwise.
3rd parties can decide if they want to bundle the service with their product or not, but core applications from our system will have it installed.
I will mark this as the answer in a few days if no one has a better option. I was hoping there was a way to execute our assembly as a new process, but all roads to do this do not seem very reliable.
I have a C# application that should only be used when the network is down, but am afraid users will just unplug the network cable in order to use it.
Is there a way to detect if the network cable has been unplugged?
Thanks
You could use IsNetworkAlive(). Although technically it doesn't check link state, it's probably better since it can detect wireless and dialup connectivity as well. Here's an example:
using System.Runtime.InteropServices;
class Program
{
[DllImport("sensapi.dll")]
static extern bool IsNetworkAlive(out int flags);
static void Main(string[] args)
{
int flags;
bool connected = IsNetworkAlive(out flags);
}
}
The flags param returns whether the connection is to the internet or just a LAN. I'm not 100% sure how it knows, but I'd bet it just looks to see if there is a default gateway set.
In my humble opinion, there is no certain way to distinguish between a network down and an unplugged cable. And even if there is a way, there is also a way to work around it.
Let's assume that you have a solution and let's look at some situations:
There is no network traffic, the cable is not unplugged from the computer: it may be unplugged at the other end.
There is no network traffic, the cable is unplugged: but this has always been the case, the laptop is connected via Wi-Fi, which is down at the moment.
There are several network interfaces, only the one connected to WAN is down: should your app work?
The network is actually down, in the sense you mean: someone has managed to reboot the router continuously for using your app.
You can use this
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
Some network drivers are able to detect this. However you'd need to use unmanaged code to access them from C# (which may be very difficult/impossible) and the solution may not be reliable for all network adapters.
The network card will report this as a state. Tools like ethtool can display this (Link up), but that is only available for Linux/Unix.
If you can enumerate the installed network cards with a Windows API, I'm sure you'll find the flag for "link up" somewhere in there.
You could register a delegate to the NetworkChange Class. When a network change occurs, it doesn't actually notify you what happened, so you could list all the network interfaces (Using NetworkInterface), filter the ones that concern you (By checking there properties) and check their operational status.
If I really wanted to use your application and whether it will work depends on something like this, I would always be able to find a way to trick your application. Are you sure there's no better solution?
How about pinging the default gateway?
There is some code here that gets the default gateway from the registry.
To detect 'Is network cable plugged in a machine?', below piece of code works.
class Program
{
private static void Main(string[] args)
{
bool isNetworkCableConnected = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
}
}
I wish to write a windows app which does something when I become disconnected from the internet. I was thinking of writing a very simple C#/Delphi app which simply polls every 20 seconds to see if I'm still connected.
If I have to poll I'd really like a solution other than trying to download a web page from the net. I can't assume that a download attempt failing means "not online" since there may be other apps eating up the internet bandwidth. Plus I'm sure constantly connecting/downloading from a particular site is going to get my IP blocked.
I'm sure there's a way to tell if you're online without downloading/connecting to a remote server but I'm not sure how.
Beware that connected to the Internet does not really mean anything: what if you are connected to your ISP, but the backbone is down, or all the sites you want to access are in a country that went off the grid like recently? Having a connection does not mean you can do what you want.
Anyway, as stated before you can use the InternetGetConnectedState API to test that you have a valid Internet connection configured.
As an example, the following routine told me correctly I had a LAN Connection, but failed to detect that I had my ZoneAlarm firewall set to block "All Internet Activity", which means that you effectively lost all Internet connectivity.
Delphi routine:
procedure IsConnected;
var
dwFlags: DWORD;
begin
if InternetGetConnectedState(#dwFlags, 0) then
begin
if (dwFlags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then
ShowMessage('Modem Connection')
else
if (dwFlags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then
ShowMessage('LAN Connection')
else
if (dwFlags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then
ShowMessage('Connection thru Proxy')
else
if (dwFlags and INTERNET_CONNECTION_OFFLINE) = INTERNET_CONNECTION_OFFLINE then
ShowMessage('Local system in offline mode')
else
if (dwFlags and INTERNET_CONNECTION_CONFIGURED) = INTERNET_CONNECTION_CONFIGURED then
ShowMessage('Valid connection exists, but might or might not be connected')
end
else
ShowMessage('Not Connected. Try to connect and risk of being prompted to dial into another Internet Service Provider.');
end;
Call the InternetGetConnectedState function. This knowledgebase article explains how to do it.
It looks like it can be done by using the method described here: http://www.csharphelp.com/archives3/archive499.html