How to determine which network adapter is connecte

2019-01-28 00:45发布

I'm writing a program in C# that needs to monitor the amount of internet bandwidth currently in use so it can do a background upload when the internet usage is low. How can I automatically determine which network adapter is the one connected to the internet?

5条回答
beautiful°
2楼-- · 2019-01-28 00:56

Examine the routing table and look for the interfaces that have a default route (a route to 0.0.0.0) - that's your interface(s) that are connected to the wider world (if any).

查看更多
做个烂人
3楼-- · 2019-01-28 01:02

See here for a similar question on how to monitor the bandwidth used, in VB.NET, but the philosophy is the same! Here is another question that is the fastest way of checking for internet connection.

Hope this helps, Best regards, Tom.

查看更多
该账号已被封号
4楼-- · 2019-01-28 01:05

You can use WMI to query all the adapters and see which one is connected.
This article shows you how to do it in VB.Net (very easily transferable to C#).

查看更多
男人必须洒脱
5楼-- · 2019-01-28 01:06

I ended up following a link to MSDN when I was reading this page where I found the GetBestInterface function. I was able to use that to find the adapter thats connected to the internet

查看更多
做自己的国王
6楼-- · 2019-01-28 01:11

There are any number of ways an adapter may show as "connected to the internet" when it isn't. Conversely, it's possible for it to "not be connected to the internet" and still be connected.

Like many things in life, "The proof of the pudding is in the eating" If you want to know if you're connected, you'll need to try to talk to something.

I like time.gov since it returns a tiny chunk of XML containing the current time so you can make sure you're actually connecting to the net and not getting some sort of cached data or a redirect to a captive portal.

Just loop through the adapters and see which actually has connectivity.

查看更多
登录 后发表回答