Solved

disable network adapter

Posted on 2012-04-11
11
513 Views
Last Modified: 2013-11-26
hello there,
when I right click on a network adapter (Local Area Connection) from (network connection) I see a button disable
I click it and it shows a little window "internet disabled" then it disappears..
how can I accomplish that same thing using code for VS2010
0
Comment
Question by:XK8ER
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 7

Expert Comment

by:redbmaster
ID: 37835015
This is the only VBScript that I know of to disable a network adapter:

'Declare Error levels
Option Explicit

' Delcare variables
Dim objShell, objCP, objEnable, objDisable, colNetwork
Dim clsConn, clsLANConn, clsVerb
Dim strNetConn, strConn, strEnable, strDisable
Dim bEnabled, bDisabled

' Declare Name of Network Connections folder and Name of NIC
strNetConn = "Network Connections"
strConn = "Build Network"

strEnable = "En&able"
strDisable = "Disa&ble"

' Create Objects
Set objShell = CreateObject("Shell.Application")
Set objCP = objShell.Namespace(3)

Set colNetwork = Nothing

' Find Network Connections Folder
For Each clsConn in objCP.Items
	If clsConn.Name = strNetConn Then
		Set colNetwork = clsConn.getfolder
		Exit For
	End If
Next

' Error Check if folder is found
If colNetwork is Nothing Then
	WScript.Echo "Network folder not found"
	WScript.Quit
End If

Set clsLANConn = Nothing

' Find the Build Network Connection
For Each clsConn in colNetwork.Items
	If LCase(clsConn.name) = LCase(strConn) Then
		Set clsLANConn = clsConn
		Exit For
	End If
Next

' Error Check if Network Connection is found or not
If clsLANConn is Nothing Then
	WScript.Echo "Network Connection not found"
	WScript.Quit
End If

bEnabled = True
Set objEnable = Nothing
Set objDisable = Nothing
bEnabled = false

' Disable NIC
For Each clsVerb in clsLANConn.verbs
	If clsVerb.name = strDisable Then 
		Set objDisable = clsVerb 
		bEnabled = True
	End If

Next

If bEnabled = True Then
	objDisable.DoIt
End If

'Give the connection time to stop/start
WScript.Sleep 1000 

Open in new window


Hopefully, that will help.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37835267
0
 
LVL 27

Expert Comment

by:Chinmay Patel
ID: 37835944
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 1

Author Comment

by:XK8ER
ID: 37836299
I tried the 3 solutions posted here but they're not working..
0
 
LVL 1

Author Comment

by:XK8ER
ID: 37867756
if anyone could help me get this running on vb.net or at least C# I would appreciate it..
0
 
LVL 27

Expert Comment

by:Chinmay Patel
ID: 37868409
What happens when you run the code suggested?
0
 
LVL 1

Author Comment

by:XK8ER
ID: 37868630
i dont see any c# or vb.net code?
0
 
LVL 27

Accepted Solution

by:
Chinmay Patel earned 500 total points
ID: 37869229
oh ok..

see this is a hyper link... : http://lamahashim.blogspot.in/2010/03/disabling-network-using-c.html

when you click on it it takes you to another web resource.

if you click on the link given earlier it will indeed take you to a web page where you can read some text like this :



/// <summary>
/// This is a generic class for disconnecting TCP connections.
/// This class can be used to
/// 1. Get a list of all connections.
/// 2. Cloas a connection
/// </summary>
public static class DisconnectWrapper
{
/// <summary>
/// Enumeration of connection states
/// </summary>
public enum ConnectionState
{
All = 0,
Closed = 1,
Listen = 2,
Syn_Sent = 3,
Syn_Rcvd = 4,
Established = 5,
Fin_Wait1 = 6,
Fin_Wait2 = 7,
Close_Wait = 8,
Closing = 9,
Last_Ack = 10,
Time_Wait = 11,
Delete_TCB = 12
}

/// <summary>
/// Connection information
/// </summary>
private struct ConnectionInfo
{
public int dwState;
public int dwLocalAddr;
public int dwLocalPort;
public int dwRemoteAddr;
public int dwRemotePort;
}

/// <summary>
/// Win 32 API for get all connection
/// </summary>
/// <param name="pTcpTable">Pointer to TCP table</param>
/// <param name="pdwSize">Size</param>
/// <param name="bOrder">Order</param>
/// <returns>Number</returns>
[DllImport("iphlpapi.dll")]
private static extern int GetTcpTable(IntPtr pTcpTable, ref int pdwSize, bool bOrder);

/// <summary>
/// Set the connection state
/// </summary>
/// <param name="pTcprow">Pointer to TCP table row</param>
/// <returns>Status</returns>
[DllImport("iphlpapi.dll")]
private static extern int SetTcpEntry(IntPtr pTcprow);

/// <summary>
/// Convert 16-bit value from network to host byte order
/// </summary>
/// <param name="netshort">network host</param>
/// <returns>host byte order</returns>
[DllImport("wsock32.dll")]
private static extern int ntohs(int netshort);

/// <summary>
/// //Convert 16-bit value back again
/// </summary>
/// <param name="netshort"></param>
/// <returns></returns>
[DllImport("wsock32.dll")]
private static extern int htons(int netshort);

/// <summary>
/// Close all connection to the remote IP
/// </summary>
/// <param name="IP">IP to close</param>
public static void CloseRemoteIP(string IP)
{
ConnectionInfo[] rows = getTcpTable();
for (int i = 0; i < rows.Length; i++)
{
if (rows[i].dwRemoteAddr == IPStringToInt(IP))
{
rows[i].dwState = (int)ConnectionState.Delete_TCB;
IntPtr ptr = GetPtrToNewObject(rows[i]);
int ret = SetTcpEntry(ptr);
}
}
}

/// <summary>
/// Close all connections at current local IP
/// </summary>
/// <param name="IP">IP to close</param>
public static void CloseLocalIP(string IP)
{
ConnectionInfo[] rows = getTcpTable();
for (int i = 0; i < rows.Length; i++)
{
if (rows[i].dwLocalAddr == IPStringToInt(IP))
{
rows[i].dwState = (int)ConnectionState.Delete_TCB;
IntPtr ptr = GetPtrToNewObject(rows[i]);
int ret = SetTcpEntry(ptr);
}
}
}

/// <summary>
/// //Closes all connections to the remote port
/// </summary>
/// <param name="port">Port to close</param>
public static void CloseRemotePort(int port)
{
ConnectionInfo[] rows = getTcpTable();
for (int i = 0; i < rows.Length; i++)
{
if (port == ntohs(rows[i].dwRemotePort))
{
rows[i].dwState = (int)ConnectionState.Delete_TCB;
IntPtr ptr = GetPtrToNewObject(rows[i]);
int ret = SetTcpEntry(ptr);
}
}
}

/// <summary>
/// //Closes all connections to the local port
/// </summary>
/// <param name="port">Local port</param>
public static void CloseLocalPort(int port)
{
ConnectionInfo[] rows = getTcpTable();
for (int i = 0; i < rows.Length; i++)
{
if (port == ntohs(rows[i].dwLocalPort))
{
rows[i].dwState = (int)ConnectionState.Delete_TCB;
IntPtr ptr = GetPtrToNewObject(rows[i]);
int ret = SetTcpEntry(ptr);
}
}
}

/// <summary>
/// Close a connection by returning the connectionstring
/// </summary>
/// <param name="connectionstring">Connection to close</param>
public static void CloseConnection(string connectionstring)
{
try
{
//Split the string to its subparts
string[] parts = connectionstring.Split('-');
if (parts.Length != 4) throw new Exception("Invalid connectionstring - use the one provided by Connections.");
string[] loc = parts[0].Split(':');
string[] rem = parts[1].Split(':');
string[] locaddr = loc[0].Split('.');
string[] remaddr = rem[0].Split('.');
//Fill structure with data
ConnectionInfo row = new ConnectionInfo();
row.dwState = 12;
byte[] bLocAddr = new byte[] { byte.Parse(locaddr[0]), byte.Parse(locaddr[1]), byte.Parse(locaddr[2]), byte.Parse(locaddr[3]) };
byte[] bRemAddr = new byte[] { byte.Parse(remaddr[0]), byte.Parse(remaddr[1]), byte.Parse(remaddr[2]), byte.Parse(remaddr[3]) };
row.dwLocalAddr = BitConverter.ToInt32(bLocAddr, 0);
row.dwRemoteAddr = BitConverter.ToInt32(bRemAddr, 0);
row.dwLocalPort = htons(int.Parse(loc[1]));
row.dwRemotePort = htons(int.Parse(rem[1]));
//Make copy of the structure into memory and use the pointer to call SetTcpEntry
IntPtr ptr = GetPtrToNewObject(row);
int ret = SetTcpEntry(ptr);
if (ret == -1) throw new Exception("Unsuccessful");
if (ret == 65) throw new Exception("User has no sufficient privilege to execute this API successfully");
if (ret == 87) throw new Exception("Specified port is not in state to be closed down");
if (ret != 0) throw new Exception("Unknown error (" + ret + ")");
}
catch (Exception ex)
{
throw new Exception("CloseConnection failed (" + connectionstring + ")! [" + ex.GetType().ToString() + "," + ex.Message + "]");
}
}

/// <summary>
/// Get all connection
/// </summary>
/// <returns>Array of connection string</returns>
public static string[] Connections()
{
return Connections(ConnectionState.All);
}

/// <summary>
/// Get connections based on the state
/// </summary>
/// <param name="state"></param>
/// <returns></returns>
public static string[] Connections(ConnectionState state)
{
ConnectionInfo[] rows = getTcpTable();

ArrayList arr = new ArrayList();

foreach (ConnectionInfo row in rows)
{
if (state == ConnectionState.All || state == (ConnectionState)row.dwState)
{
string localaddress = IPIntToString(row.dwLocalAddr) + ":" + ntohs(row.dwLocalPort);
string remoteaddress = IPIntToString(row.dwRemoteAddr) + ":" + ntohs(row.dwRemotePort);
arr.Add(localaddress + "-" + remoteaddress + "-" + ((ConnectionState)row.dwState).ToString() + "-" + row.dwState);
}
}

return (string[])arr.ToArray(typeof(System.String));
}

/// <summary>
/// The function that fills the ConnectionInfo array with connectioninfos
/// </summary>
/// <returns>ConnectionInfo</returns>
private static ConnectionInfo[] getTcpTable()
{
IntPtr buffer = IntPtr.Zero; bool allocated = false;
try
{
int iBytes = 0;
GetTcpTable(IntPtr.Zero, ref iBytes, false); //Getting size of return data
buffer = Marshal.AllocCoTaskMem(iBytes); //allocating the datasize

allocated = true;
GetTcpTable(buffer, ref iBytes, false); //Run it again to fill the memory with the data
int structCount = Marshal.ReadInt32(buffer); // Get the number of structures
IntPtr buffSubPointer = buffer; //Making a pointer that will point into the buffer
buffSubPointer = (IntPtr)((int)buffer + 4); //Move to the first data (ignoring dwNumEntries from the original MIB_TCPTABLE struct)
ConnectionInfo[] tcpRows = new ConnectionInfo[structCount]; //Declaring the array
//Get the struct size
ConnectionInfo tmp = new ConnectionInfo();
int sizeOfTCPROW = Marshal.SizeOf(tmp);
//Fill the array 1 by 1
for (int i = 0; i < structCount; i++)
{
tcpRows[i] = (ConnectionInfo)Marshal.PtrToStructure(buffSubPointer, typeof(ConnectionInfo)); //copy struct data
buffSubPointer = (IntPtr)((int)buffSubPointer + sizeOfTCPROW); //move to next structdata
}

return tcpRows;
}
catch (Exception ex)
{
throw new Exception("getTcpTable failed! [" + ex.GetType().ToString() + "," + ex.Message + "]");
}
finally
{
if (allocated) Marshal.FreeCoTaskMem(buffer); //Free the allocated memory
}
}

/// <summary>
/// Object pointer
/// </summary>
/// <param name="obj"></param>
/// <returns>Pointer</returns>
private static IntPtr GetPtrToNewObject(object obj)
{
IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(obj));
Marshal.StructureToPtr(obj, ptr, false);
return ptr;
}

/// <summary>
/// IP to Int
/// </summary>
/// <param name="IP">IP Address</param>
/// <returns>Integer</returns>
private static int IPStringToInt(string IP)
{
if (IP.IndexOf(".") < 0) throw new Exception("Invalid IP address");
string[] addr = IP.Split('.');
if (addr.Length != 4) throw new Exception("Invalid IP address");
byte[] bytes = new byte[] { byte.Parse(addr[0]), byte.Parse(addr[1]), byte.Parse(addr[2]), byte.Parse(addr[3]) };
return BitConverter.ToInt32(bytes, 0);
}

/// <summary>
/// IP int to String
/// </summary>
/// <param name="IP">IP</param>
/// <returns>String</returns>
private static string IPIntToString(int IP)
{
byte[] addr = System.BitConverter.GetBytes(IP);
return addr[0] + "." + addr[1] + "." + addr[2] + "." + addr[3];
}
}

Open in new window


Now this strange looking text is actually a programming language called C#, let me know if you would want me to post a video on clickin on the link and opening the web page.
0
 
LVL 1

Author Comment

by:XK8ER
ID: 37925674
thanks
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question