How to enable Internet Connection Sharing using command line?

36

12

I can do it manually by right-clicking on a network connection, opening the Sharing tab and clicking on the "Allow other network users to connect through this computer's Internet connection" check box.

Now I need to automate this task. Is there a command-line tool or a Powershell cmdlet to accomplish this?

utapyngo

Posted 2012-09-05T12:56:38.990

Reputation: 1 713

2@SmartManoj, it is an option too, but please convert your comment to an answer and copy the script here. A link can become outdated. – utapyngo – 2020-01-23T04:47:40.103

That link doesn't even work. Also, Python on Windows, seriosly? – Free Consulting – 2020-01-28T20:01:22.650

4

Can't try this just now, but you might want to try running Process Monitor and pointing it at your Registry. See what keys/values change when you toggle & apply the setting, then write your script accordingly.

– Iszi – 2012-09-17T20:12:52.240

Related question/info over on StackOverflow: Enable Internet Connection Sharing programmatically

– Ƭᴇcʜιᴇ007 – 2013-03-17T17:35:37.417

The Microsoft-Windows-SharedAccess Unattended Windows Setup component is so close, but it only works at Windows Setup! http://technet.microsoft.com/en-us/library/ff715511.aspx

– Jacob Krall – 2013-09-20T20:26:42.493

Answers

21

Here is a pure PowerShell solution (should be run with administrative privileges):

# Register the HNetCfg library (once)
regsvr32 hnetcfg.dll

# Create a NetSharingManager object
$m = New-Object -ComObject HNetCfg.HNetShare

# List connections
$m.EnumEveryConnection |% { $m.NetConnectionProps.Invoke($_) }

# Find connection
$c = $m.EnumEveryConnection |? { $m.NetConnectionProps.Invoke($_).Name -eq "Ethernet" }

# Get sharing configuration
$config = $m.INetSharingConfigurationForINetConnection.Invoke($c)

# See if sharing is enabled
Write-Output $config.SharingEnabled

# See the role of connection in sharing
# 0 - public, 1 - private
# Only meaningful if SharingEnabled is True
Write-Output $config.SharingType

# Enable sharing (0 - public, 1 - private)
$config.EnableSharing(0)

# Disable sharing
$config.DisableSharing()

See also this question at social.msdn.microsoft.com:

You have to enable the public interface on the adapter you are connecting to and enable sharing on the private interface for the adapter you want to be able to use for the network.

utapyngo

Posted 2012-09-05T12:56:38.990

Reputation: 1 713

@utapyngo, the same error on Windows 10, An event was unable to invoke any of the subscribers (Exception from HRESULT: 0x80040201). – Suncatcher – 2017-03-07T20:58:15.457

1Ooh, I didn't know you could do COM interop with PowerShell! I assume you need some [System.Runtime.Interopservices.Marshal]::ReleaseComObject(...) sprinkled in. – Jacob Krall – 2013-09-23T16:19:46.357

The call to EnableSharing is throwing this exception, even though I'm running PowerShell as Administrator:Exception: Exception calling "EnableSharing" with "1" argument(s): "An event was unable to invoke any of the subscribers (Exception from HRESULT: 0x80040201)" --> Exception has been thrown by the target of an invocation. --> An event was unable to invoke any of the subscribers (Exception from HRESULT: 0x80040201) – Jacob Krall – 2013-09-23T20:36:11.920

Try running regsvr32 hnetcfg.dll as administrator manually. – utapyngo – 2013-09-24T02:19:32.710

I wonder: what does "enable the public interface on the adapter" mean? – Jacob Krall – 2013-09-24T16:36:12.670

I think it means .EnableSharing(0) but you have already figured it out. – utapyngo – 2013-09-25T11:18:24.580

2In newer versions of Powershell, .SharingType is now .SharingConnectionType – Baodad – 2013-12-28T18:15:29.700

9

I have created a simple command line tool for this.

  1. Download and unzip or git clone git@github.com:utapyngo/icsmanager.git

  2. Build by running build.cmd

  3. Register the HNetCfg COM library: regsvr32 hnetcfg.dll (it is a standard library located at %WINDIR%\System32)

Command-line usage

  1. Open the command line prompt as administrator

    cd to the icsmanager directory (or icsmanager-master if you downloaded zip).

  2. Type icsmanager

    This should display available network connections. Notice the GUID attribute. To use this tool you need to have at least two connections.

  3. Type icsmanager enable {GUID-OF-CONNECTION-TO-SHARE} {GUID-OF-HOME-CONNECTION}

    This should enable ICS.

Powershell usage

  1. Import module:

    Import-Module IcsManager.dll

  2. List network connections:

    Get-NetworkConnections

  3. Start Internet Connection Sharing:

    Enable-ICS "Connection to share" "Home connection"

  4. Stop Internet Connection Sharing:

    Disable-ICS


Disclaimer: I did not test the tool yet. Use it at your own risk. Feel free to open an issue at GitHub if something does not work. Pull requests are also welcome.

utapyngo

Posted 2012-09-05T12:56:38.990

Reputation: 1 713

@BBK I had this problem also, and solved it by running MSBuild in a Visual Studio developer command prompt. But I also found I had to open IcsManager.sln in Visual Studio and change the target framework to a later version (4.6 in my case using VS2015). – Neo – 2015-12-12T19:57:31.953

Neat. This uses an external binary called NETCONLib; where did it come from? What does it do? – Jacob Krall – 2013-09-23T15:09:44.057

Aha. This is a COM class wrapper for the "NetCon 1.0 Type Library" included with Windows. – Jacob Krall – 2013-09-23T15:18:03.323

@JacobKrall, yes, it is located at C:\Windows\System32\hnetcfg.dll. – utapyngo – 2013-09-23T15:53:52.887

This looks like it will do exactly what I want - I will try it out. – Jacob Krall – 2013-09-23T16:13:37.903

How did you learn about hnetcfg.dll? – Jacob Krall – 2013-09-23T16:15:15.753

Argh! This one also has the HRESULT: 0x80040201 exception in the cmdlet, command line, and GUI too. – Jacob Krall – 2013-09-23T20:50:23.520

1

Sorry, I did it several months ago and forgot that HNetCfg should be registered manually with regsvr32 hnetcfg.dll. And I learnt about hnetcfg.dll at http://msdn.microsoft.com/en-us/library/windows/desktop/aa365960%28v=vs.85%29.aspx

– utapyngo – 2013-09-24T14:16:25.277

Well, regsvr32 hnetcfg.dll gets it halfway there - $homeConnConfig.EnableSharing(1) succeeds, but $publicConnConfig.EnableSharing(0) still throws HRESULT: 0x80040201. I wish it would give a better error! – Jacob Krall – 2013-09-24T16:27:04.460

Try this hotfix: http://support.microsoft.com/kb/926997/en-us

– utapyngo – 2013-09-25T02:41:04.693

For some reason, it started working yesterday right before I left work. I don't think that hotfix would have fixed it, though, because it's for .NET 2.0; Win8 comes with 4.5. Also, I got the same error from VBScript. I bet it was just some corruption on my computer. We'll see how the rollout goes. Thanks for all the help! – Jacob Krall – 2013-09-25T14:19:09.853

Do I need nore then .Net 4.0? You may be able to solve the problem by doing one of the follo wing: 1) Install the Microsoft Windows SDK. 2) Install Visual Studio 2010. 3) Manually set the above registry key to the correct location. 4) Pass the correct location into the "ToolPath" parameter of the task. [D:\HP\Downloads\icsmanager-master\IcsManagerLibrary\IcsManagerLibrary.csproj] – BBK – 2013-11-23T00:29:47.013

4

By my understanding, routing capability was removed from Windows since Vista and is only available now in Windows Server.

The following trick can be found on the Internet to re-enable netsh routing, which you can try at your own risk. I suggest first the usual precautions, including creating a system restore point.

  1. Get IPMONTR.DLL and IPPROMON.DLL from 2003 or from XP
  2. Copy them to WINDOWS\SYSTEM32
  3. Run in Command Prompt (cmd) as administrator :

    netsh add helper ipmontr.dll
    netsh add helper ippromon.dll

You might also need to set the Routing and Remote Access Service to Automatic startup.

Reboot before trying anything.

harrymc

Posted 2012-09-05T12:56:38.990

Reputation: 306 093

-1 this was a solution for Vista but these netsh helpers no longer loads in 7 regardless of architecture (since "helper" is an add-in DLL, architecture must also match) – Free Consulting – 2020-01-28T20:10:37.227

1Is it legal to copy files from XP if I don't have XP license? – utapyngo – 2013-09-24T13:22:28.843

1Tried this on Windows 7 64bit. Copied the files from XP 64 bit. Running as administrator. Errors: The following helper DLL cannot be loaded: IPMONTR.DLL. The following helper DLL cannot be loaded: IPPROMON.DLL. – utapyngo – 2013-09-24T14:14:33.893

1I tried it too the "add helper" and I am sorry to confirm that it doesn't work for 64-bit. As regarding the legality of transplanting dlls to which you have right on both OSs, this is unclear. You don't have the right to modify Windows files, but copying them is maybe not ruled against in the XP license (it would astound me that Microsoft could have foreseen this in advance). – harrymc – 2013-09-24T18:30:56.683

1It should be mentioned in the answer that it does not work for 64-bit Windows. Please also mention that the files should be copied from XP 32-bit. – utapyngo – 2013-09-25T01:35:58.303

@utapyngo: One cannot be sure that there is really is no way to make this work on 64-bit. According to my studies, the problem is that more dlls than these two should be copied, but analyzing fully the problem requires more time than I can give. – harrymc – 2013-09-25T05:47:30.590

2

Unfortunately there is no such cmd command for Windows 7 or more, so I used this Visual Basic function to get it done:

Private Function EnableDisableICS(ByVal sPublicConnectionName As String, ByVal sPrivateConnectionName As String, ByVal bEnable As Boolean)  
    Dim bFound As Boolean
    Dim oNetSharingManager, oConnectionCollection, oItem, EveryConnection, objNCProps
    oNetSharingManager = CreateObject("HNetCfg.HNetShare.1")
    oConnectionCollection = oNetSharingManager.EnumEveryConnection
    For Each oItem In oConnectionCollection
        EveryConnection = oNetSharingManager.INetSharingConfigurationForINetConnection(oItem)
        objNCProps = oNetSharingManager.NetConnectionProps(oItem)
        If objNCProps.name = sPrivateConnectionName Then
            bFound = True
            MsgBox("Starting Internet Sharing For: " & objNCProps.name)
            If bEnable Then
                EveryConnection.EnableSharing(1)
            Else
                EveryConnection.DisableSharing()
            End If
        End If
    Next
    oConnectionCollection = oNetSharingManager.EnumEveryConnection
    For Each oItem In oConnectionCollection
        EveryConnection = oNetSharingManager.INetSharingConfigurationForINetConnection(oItem)
        objNCProps = oNetSharingManager.NetConnectionProps(oItem)
        If objNCProps.name = sPublicConnectionName Then
            bFound = True
            MsgBox("Internet Sharing Success For: " & objNCProps.name)
            If bEnable Then
                EveryConnection.EnableSharing(0)
            Else
                EveryConnection.DisableSharing()
            End If
        End If
    Next
    Return Nothing 'bEnable & bFound
End Function  

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    EnableDisableICS("YOUR ACTIVE NETWORK", "YOUR ADAPTOR TO SHARE", True)
End Sub

Please note that """" is required. Have fun.

imad latch

Posted 2012-09-05T12:56:38.990

Reputation: 21

1

The following should work

netsh routing ip autodhcp install
netsh routing ip autodhcp set interface name="Local Area Connection(or whereever your internet connection is from)" mode=enable
netsh routing ip autodhcp set global 192.168.0.1 255.255.255.0 11520

Craig

Posted 2012-09-05T12:56:38.990

Reputation: 19

8It was possible to do with netsh routing in Windows XP but in Windows 7 they have removed that command. That's why I'm only asking about Windows 7. – utapyngo – 2013-01-03T04:54:12.480

1

Based on what I have read, if those that have posted said netsh doesn't work starting at 7 and up- that is incorrect. Now if it's strictly about "netsh routing", I guess you could be right, but this does work- I am about to show the contents of a batch file I have created that works on Windows 8.1. Instead of getting the usual comments and pieces of information, I am going to try and help those with the full information.

First, you need to make sure the connection you will be sharing is set to actually share the connection. This link here should get you going for that:

Set up a shared Internet connection using ICS (Internet Connection Sharing) at Windows Help.

  1. Open Network Connections by clicking the Start button, and then clicking Control Panel. In the search box, type adapter, and then, under Network and Sharing Center, click View network connections.

  2. Right-click the connection that you want to share, and then click Properties. If you're prompted for an administrator password or confirmation, type the password or provide confirmation.

  3. Click the Sharing tab, and then select the Allow other network users to connect through this computer’s Internet connection check box.

After you've followed the steps above to set up ICS on the host computer, make the following changes on all of the other computers (but not on the host computer).

  1. Open Internet Options by clicking the Start button, clicking Control Panel, clicking Network and Internet, and then clicking Internet Options.

  2. Click the Connections tab, and then click Never dial a connection.

  3. Click LAN Settings.

  4. In the Local Area Network (LAN) Settings dialog box, Under Automatic configuration, clear the Automatically detect settings and Use automatic configuration script check boxes.

  5. Under Proxy server, clear the Use a proxy server for your LAN check box, and then click OK.

Similar instructions are also available here.

To my knowledge, I think this should work for both Windows 7 and 8.

Now since the topic was about a command line solution, this is the batch file contents of how I get a virtual wireless adapter configured and ready to go.

Once it's created, you may have to use the instructions above and make sure you are sharing the source connection with the newly created virtual adapter that will be seen by your wireless devices.

Connection sharing .bat file:

@echo off
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%

cd\
    if NOT EXIST "C:\TEMP\switch.txt" (
        GOTO :START
    ) ELSE (
        GOTO :STOP
    )

:START
REM Create Temp File for On and Off switch.
ECHO WOOHOO >"C:\TEMP\switch.txt"

REM -- Output everything that is happening into a file called wifi.txt.
REM -- Start out with a timestamp at the top to show when it was done.
REM -- All 'netsh' commands are for setting up the SSID and starting the    sharing.
REM -- I stop and start when starting the service just for prosperity.

echo _%_my_datetime% >"C:\TEMP\wifi.txt"
netsh wlan set hostednetwork mode=allow ssid=ITWORKS key=111222333 >>    "C:\TEMP\wifi.txt"
netsh wlan stop hostednetwork >>"C:\TEMP\wifi.txt"
netsh wlan start hostednetwork >>"C:\TEMP\wifi.txt"
echo MSGBOX "Wifi Sharing Started!" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q
GOTO :END


REM -- This will turn ICS off and give a prompt via VBS that you're turned off.
REM -- I timestamp when the service is turned off in the output file.
REM -- I delete the switch file to let the code know to turn it on when
REM -- when fired off again.  Tempmessage is the msgbox used to show the service
REM -- has been turned off.  Same for the msgbox above when it's on.

:STOP
echo OFF AT _%_my_datetime% >>"C:\TEMP\wifi.txt"
netsh wlan stop hostednetwork >>"C:\TEMP\wifi.txt"
DEL /Q "C:\TEMP\switch.txt"
echo MSGBOX "Wifi Sharing Stopped!" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q

:END

I'll be more than happy to answer questions about this because there is going to be some unique situations and I'd like to help since I had to piece together what I found above.

But to bring this to perspective, this works on Windows 8.1 using an Ethernet connection into a laptop sharing its connection to the virtual adapter. It may work just as well if you are trying to share a source Wireless connection.

user2562950

Posted 2012-09-05T12:56:38.990

Reputation: 11

Welcome to Super User! Thanks for the detailed answer, I have edited to your question to streamline some of the text and to put your bat file contents in a code block. You can see other formatting instructions if there are any problems with it- please check to make sure I haven't altered the meaning of the code.

– bertieb – 2015-08-02T18:43:02.973

Yeah that's fine and thanks. I knew I should have done a better job on the formatting. Nice touch on the MS link to prevent from having to actually go there. – user2562950 – 2015-08-03T19:05:39.250

Don't worry about it, you'll pick up the markdown syntax quickly enough :) Including the link content is part of a policy here on answering questions - links can go stale, change or disappear. This is less likely in the case of Microsoft, but still very possible. It is good practice to put everything necessary for a solution in the answer itself. Look forward to seeing more good answers from you!

– bertieb – 2015-08-03T20:42:06.460

In 1st numbered list one have to select the source of the Internet – SmartManoj – 2020-01-20T01:48:58.423

Sorry, but this is completely off-topic. In this answer ICS controlled manually via GUI, the rest of the text is basically well-known netsh wlan hostednetwork commands with common misconceptions. – Free Consulting – 2020-01-28T20:38:04.873

@bertieb: Actually, Microsoft is notorious for deleting pages and breaking links. In fact, the one here is broken — possibly because they’re tearing down Windows 7 pages, now that it’s out of support. – Scott – 2020-01-29T07:23:50.937

Point Free Consulting? – user2562950 – 2020-01-29T21:27:39.960