WifiSitter initial code, need disable/enable code.

servicizing
Sean McArdle 2016-03-23 14:01:55 -07:00
parent 53450d7a0b
commit f1a66eae31
5 changed files with 341 additions and 0 deletions

22
WifiSitter.sln Normal file
View File

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WifiSitter", "WifiSitter\WifiSitter.csproj", "{B3A5D84A-C7A0-409D-881D-1D5FF36773D4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B3A5D84A-C7A0-409D-881D-1D5FF36773D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3A5D84A-C7A0-409D-881D-1D5FF36773D4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3A5D84A-C7A0-409D-881D-1D5FF36773D4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3A5D84A-C7A0-409D-881D-1D5FF36773D4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

6
WifiSitter/App.config Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>

216
WifiSitter/Program.cs Normal file
View File

@ -0,0 +1,216 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Threading;
namespace WifiSitter
{
class Program
{
internal static readonly List<NetworkInterface> initialNicState = NetworkInterface.GetAllNetworkInterfaces().ToList();
static void Main(string[] args) {
var netstate = new NetworkState();
Console.WriteLine("Initialized...");
bool go = true;
while (go) {
Thread.Sleep(100);
if (netstate.CheckNet) {
var _nics = netstate.Nics;
var color = netstate.NetworkAvailable ? ConsoleColor.Green : ConsoleColor.Red;
var stat = netstate.NetworkAvailable ? "is" : "not";
Console.ForegroundColor = color;
Console.WriteLine("\n{0,48}", String.Format("Connection {0} available", stat));
Console.ResetColor();
foreach (var adapter in _nics) {
IPInterfaceProperties properties = adapter.GetIPProperties();
Console.WriteLine("{0,48} {1,16} {2}", adapter.Description, adapter.NetworkInterfaceType, adapter.OperationalStatus);
}
var wifi = _nics.Where(x => x.NetworkInterfaceType == NetworkInterfaceType.Wireless80211).Where(x => x.OperationalStatus == OperationalStatus.Up);
if (netstate.NetworkAvailable) { // Network available
if (netstate.EthernetUp) { // Ethernet is up
if (wifi != null) {
foreach (var adapter in wifi) {
DisableAdapter(adapter);
}
}
}
}
else { // Network unavailable
CheckWifiNicsAndEnable(initialNicState, _nics);
}
Console.WriteLine("\n");
netstate.StateChecked();
}
}
}
private static void CheckWifiNicsAndEnable(List<NetworkInterface> InitialState, List<NetworkInterface> CurrentState) {
var initialIds = InitialState.Select(x => x.Id).ToArray();
var currentIds = CurrentState.Select(x => x.Id).ToArray();
Console.ForegroundColor = ConsoleColor.Yellow;
foreach (var nic in InitialState) {
if ( !initialIds.Contains(nic.Id)
&& !currentIds.Contains(nic.Id)) {
Console.WriteLine("Adapter existed initialy but doesn't now, assuming disabled: {0}", nic.Description);
EnableAdapter(nic);
}
}
Console.ResetColor();
}
private static void EnableAdapter(NetworkInterface nic) {
Console.WriteLine("Enable adaptor {0}", nic.Description);
}
private static void DisableAdapter(NetworkInterface nic) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Disable adaptor {0}", nic.Description);
Console.ResetColor();
}
}
public class NetworkState
{
#region fields
private List<NetworkInterface> _nics;
private bool _checkNet;
private bool _netAvailable;
#endregion // fields
#region constructor
/// <summary>
/// Constructor, initializes nics list and sets up event handlers.
/// </summary>
public NetworkState () {
this.Nics = QueryNetworkAdapters();
Initialize();
}
/// <summary>
/// Constructor, initializes nics list and sets up event handlers.
/// </summary>
/// <param name="Nics"></param>
public NetworkState (List<NetworkInterface> Nics) {
this.Nics = Nics;
Initialize();
}
private void Initialize() {
CheckNet = true;
_netAvailable = NetworkInterface.GetIsNetworkAvailable();
NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged; ;
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
~NetworkState() {
NetworkChange.NetworkAddressChanged -= NetworkChange_NetworkAddressChanged; ;
NetworkChange.NetworkAvailabilityChanged -= NetworkChange_NetworkAvailabilityChanged;
}
#endregion // constructor
#region methods
public void StateChecked () {
this.CheckNet = false;
}
public void UpdateNics (List<NetworkInterface> Nics) {
this.Nics = Nics;
}
internal static List<NetworkInterface> QueryNetworkAdapters() {
return NetworkInterface.GetAllNetworkInterfaces().Where(x => (x.NetworkInterfaceType != NetworkInterfaceType.Loopback && x.NetworkInterfaceType != NetworkInterfaceType.Tunnel)).ToList();
}
#endregion // methods
#region properties
public bool EthernetUp {
get {
if (Nics == null) return false;
return Nics.Where(x => x.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
.Any(x => x.OperationalStatus == OperationalStatus.Up);
}
}
public List<NetworkInterface> Nics {
get {
if (_nics == null) return new List<NetworkInterface>();
return _nics;
}
private set {
_nics = value;
}
}
public bool CheckNet {
get {
return _checkNet;
}
private set {
_checkNet = value;
}
}
public bool NetworkAvailable {
get {
return _netAvailable;
}
private set { _netAvailable = value; }
}
#endregion // properties
#region eventhandlers
private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) {
_netAvailable = NetworkInterface.GetIsNetworkAvailable();
_nics = QueryNetworkAdapters();
_checkNet = true;
}
private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e) {
_netAvailable = NetworkInterface.GetIsNetworkAvailable();
_nics = QueryNetworkAdapters();
_checkNet = true;
}
#endregion // eventhandlers
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WifiSitter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WifiSitter")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b3a5d84a-c7a0-409d-881d-1d5ff36773d4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B3A5D84A-C7A0-409D-881D-1D5FF36773D4}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WifiSitter</RootNamespace>
<AssemblyName>WifiSitter</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>