C# 测试活动的互联网连接。ping google.com

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/801075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:44:28  来源:igfitidea点击:

C# Testing active internet connection. Pinging google.com

c#networking

提问by ant2009

C# 2008

C# 2008

I am using this code to test for an internet connection. As my application will have to login to a web server. However, if the user internet connection was to fail or cable pulled out. I will have to notify the user.

我正在使用此代码来测试互联网连接。因为我的应用程序必须登录到 Web 服务器。但是,如果用户互联网连接失败或电缆拔出。我将不得不通知用户。

 // Ping www.google.com to check if the user has a internet connection.
    public bool PingTest()
    {
        Ping ping = new Ping();

        PingReply pingStatus = ping.Send(IPAddress.Parse("208.69.34.231"));

        if (pingStatus.Status == IPStatus.Success)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

The only way I think I can test for an Internet connection is to ping www.google.com. So I have a used a server timer which I have set for 500 milliseconds and in the lapsed event it will call this ping function. If the ping returns false. Then my app will take appropriate action.

我认为可以测试 Internet 连接的唯一方法是 ping www.google.com。所以我使用了一个服务器计时器,我将它设置为 500 毫秒,并且在失效事件中它会调用这个 ping 函数。如果 ping 返回 false。然后我的应用程序将采取适当的行动。

Do you think using google as a way to test an Internet connect is a good thing. If google was to fail, then my app would not function. Is polling 1/2 second to much or too little? Just wondering about my whole idea if it is good or not?

你认为使用谷歌作为测试互联网连接的一种方式是一件好事。如果谷歌失败,那么我的应用程序将无法运行。轮询 1/2 秒是多还是少?只是想知道我的整个想法是否好?

Many thanks,

非常感谢,

采纳答案by Jon Skeet

Why ping Google? The only server you really care about is the web server you want to talk to, right? So ping that instead. That way, you can notify the user if anything is wrong between them and the web server - that's the only thing that matters.

为什么要 ping 谷歌?您真正关心的唯一服务器是您要与之通信的 Web 服务器,对吗?所以改为ping那个。这样,如果用户和 Web 服务器之间出现任何问题,您可以通知用户 - 这是唯一重要的事情。

If something goes wrong with the internet which means that the user can only do anything within their own town, you may not be able to reach Google but if you can still reach the web server you're interested in, why report a problem? On the other hand, if the web server goes down but Google doesn't, why would you notwant to tell the user that there's a problem?

如果互联网出现问题,这意味着用户只能在他们自己的城镇内做任何事情,您可能无法访问 Google,但如果您仍然可以访问您感兴趣的网络服务器,为什么要报告问题?在另一方面,如果Web服务器出现故障,但谷歌没有,为什么你会不会想告诉用户,有一个问题?

Likewise, why use a ping? Why not send an HTTP request to a known URL on the web server? After all, if the network is up but the web server process itself is down, surely that's just as bad as the user's network going down.

同样,为什么要使用 ping?为什么不向 Web 服务器上的已知 URL 发送 HTTP 请求?毕竟,如果网络已启动但 Web 服务器进程本身已关闭,那肯定与用户的网络故障一样糟糕。

EDIT: I hadn't noticed in the question that you were repeating this every half second. That's really not pleasant for anyone. Surely once a minute is often enough, isn't it?

编辑:我没有注意到你每半秒重复一次这个问题。这对任何人来说都不是很愉快。肯定一分钟一次就足够了,不是吗?

回答by Jakub Arnold

It'd suggest to put more than 0.5s, because sometimes your lataency can get higher. I sometimes have even 3.5s on DSL.

建议设置超过 0.5 秒,因为有时您的延迟会更高。我有时在 DSL 上什至有 3.5 秒。

回答by Skittles

I might be missing something but, Why do you need to test that the server is up and the web service running before you need to use it? If you call a method in your web services and you don't get a timely response, then take what ever action you see fit or need?

我可能遗漏了一些东西,但是,为什么在需要使用它之前需要测试服务器已启动并且 Web 服务正在运行?如果您在 Web 服务中调用一个方法并且没有得到及时响应,那么采取您认为合适或需要的任何操作?

It just seems over engineering of the design.

它似乎只是设计的工程。

[edit]

[编辑]

Thanks for the clarification robUK. You should listen to NET Rocks podcast episode 'Udi Dahan Scales Web Applications!' (date 12/08/2008). They discuss adding a GUID to a request and wait until you get the same GUID in the response. Maybe you could fire it off every second for say 10 attempts and if you don't get a response back (with the GUID attached) after 10 attempts, then take the required action?

感谢 robUK 的澄清。您应该收听 NET Rocks 播客节目“Udi Dahan Scales Web Applications!” (日期 12/08/2008)。他们讨论向请求添加 GUID 并等待您在响应中获得相同的 GUID。也许你可以每秒触发一次,比如 10 次尝试,如果你在 10 次尝试后没有得到回复(附有 GUID),然后采取必要的行动?

Good luck with it..

祝你好运。。

回答by JP Alioto

I have an app that needs to do something similar. We have a bit of a different architecture in place, namely a pub/sub message bus. For those applications interested in hearing "heartbeats" from the various services, we allow them to register their interest with the bus. Every few second or so, each service will publish a health state message that consumers will then receive. If the consumers do not receive a health state message for a certain amount of time, they can take appropriate action until they hear it again.

我有一个需要做类似事情的应用程序。我们有一些不同的架构,即发布/订阅消息总线。对于那些有兴趣从各种服务中听到“心跳”的应用程序,我们允许他们向总线注册他们的兴趣。每隔几秒左右,每个服务都会发布一条消费者随后将收到的健康状态消息。如果消费者在一段时间内没有收到健康状态消息,他们可以采取适当的行动,直到他们再次听到它。

This setup is much more scalable than polling the server or even worse pinging it. Imagine if you had 100 or 1000 clients all polling or pinging your sever every few seconds. Bad.

这种设置比轮询服务器或更糟糕的 ping 服务器更具可扩展性。想象一下,如果您有 100 或 1000 个客户端每隔几秒钟轮询或 ping 您的服务器。坏的。

回答by Paul Alexander

Check out this duplicate question which has a good answer that doesn't require ping:

查看这个重复的问题,它有一个不需要 ping 的好答案:

C# - How do I check for a network connection

C# - 如何检查网络连接

You could subscribe to the System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged event and only then when it indicates that the network is down do a ping/web request to the server to see if it's available.

您可以订阅 System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged 事件,然后只有当它指示网络关闭时才向服务器执行 ping/web 请求以查看它是否可用。

回答by Kate Gregory

Better to see if you are on the network than to bother a server pinging it. See Detect Internet V. local lan connectionfor example. If you are on Windows 7 / Server 2008 R2 you can get an event when connectivity changes, which is going to be much happier for everyone than constant pinging and polling.

最好看看你是否在网络上,而不是打扰服务器 ping 它。例如,请参阅检测 Internet V. 本地 LAN 连接。如果您使用的是 Windows 7 / Server 2008 R2,您可以在连接发生变化时收到一个事件,这对每个人来说都比不断的 ping 和轮询要快乐得多。

回答by Algor

you can simply test like this

你可以简单地像这样测试

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int conn, int val);

C# full source code

C# 完整源代码

http://net-informations.com/csprj/communications/internet-connection.htm

http://net-informations.com/csprj/communications/internet-connection.htm

回答by Karl-Johan Sj?gren

Even though I agree with Jon that pinging your webserver might be the best idea I want to throw in another solution that might be used stand alone or together with an initial ping to the service.

尽管我同意 Jon 的观点,ping 您的网络服务器可能是最好的主意,但我想提出另一种解决方案,该解决方案可以单独使用或与对服务的初始 ping 一起使用。

These is a built in event on the NetworkChange-class called NetworkAvailabilityChangedthat you can use to get the overall status from Windows whether you are online or not. Just add a listener to it and then you will be notified when it changes.

这是一个建在事件上NetworkChange称为-classNetworkAvailabilityChanged无论你在线与否,你可以用它来获得从Windows的整体状态。只需向其添加一个侦听器,然后您会在它发生变化时收到通知。

private void MyForm_Load(object sender, EventArgs e)
{
    NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
}

private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
    if (e.IsAvailable)
    {
        WriteLog("Network is available again, updating items");
        timer1_Tick(sender, EventArgs.Empty);
        return;
    }

    WriteLog("Network isn't available at the moment");
}

It's available from .Net 2.0 and onward. More info can be found on MSDN.

它可从 .Net 2.0 及更高版本使用。更多信息可以在MSDN上找到。