Set static ip if not obtained from DHCP (script)
dhclient should support fallback via lease declaration
have a look at the dhclient.conf
man page.
Add something like this to your dhclient.conf
timeout 10;
lease {
interface "eth0";
fixed-address 10.0.0.10;
option subnet-mask 255.255.255.0;
renew 2 2022/1/1 00:00:01;
rebind 2 2022/1/1 00:00:01;
expire 2 2022/1/1 0:00:01;
}
or you can assign a second IP to the interface like /etc/network/interfaces
auto lo
iface lo inet loopback
iface eth0 inet dhcp
auto eth0:1
iface eth0:1 inet static
address 10.10.10.2
netmask 255.255.255.0
How to set a static IP address in windows 10?
Please note that this is the implementation of: http://www.midnightdba.com/Jen/2014/03/configure-static-or-dynamic-ip-and-dns-with-powershell/. All credits go to MidnightDBA. I hope it benefits someone!
To set the IP adress to static manually
Start>control panel>Network and Internet>Network and Sharing Center>Change adapter settings>rmb on the ethernet/wifi/connection that is in use>properties>Select: Internet Protocol Version 4(TCP/IPv4)>Properties>
That should result in the screen similar to the attached image. There you can fill in the numbers manually. These numbers will (probably) be different in your own situation, you need to do the work suggested in note 3. to determine those numbers for yourself.
To set the static IP (semi-automatically):
This means you will be able to to set the IP address to static by opening a file (double clicking a script you've made), and back to a dynamic IP address by running another script you've made. The instruction steps are listed below:
start>type Powershell>rmb>Open powershell as administrator
- (Only do this step if you can not immediately run the script the first time.) Type:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
and hit enter, to set the security policy so that you can run a powershell script. create a
.ps1
file named e.g.static_ip.ps1
in for examplec:/example_folder
with the content:$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled ='true'";
$wmi.EnableStatic("your_static_ip_adress", "your_subnetmask");
$wmi.SetGateways("your_routers_ip_adress", 1);
$wmi.SetDNSServerSearchOrder("your_dns");OR to set the static IP with just a single double click on the
static_ip.ps1
script:
(Note example values filled in)# 18-07-20 Todo: add wifi network detection that automatically triggers setting a static IP and back dynamic IP.
# First ensure the script is automatically ran as administrator, else it appearently does not have the privileges to change the local IP adress:
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}
# Next set it static:
$wmi.EnableStatic("192.21.89.5", "255.255.254.0");
$wmi.SetGateways("192.21.89.1", 1);
$wmi.SetDNSServerSearchOrder("192.21.89.1");
# Now close the window this has just created.
# This leaves other Powershell windows open if they were already open before you ran this script.
# Also, It yields an error with a $ sign at the start of the line.
# Source: https://stackoverflow.com/questions/14874619/powershell-exit-doesnt-really-exit
Stop-Process -Id $PIDThen in powershell enter:
cd c:/example_folder
.\static_ip.ps1Note, if the path to the
static_ip.ps1
file contains a space change thechange directory
-command to:cd "c:/example_folder"
To make the IP dynamic again (semi-automatically):
Create a text file named for example
dynamic_ip.ps1
located e.g. in folderc:/examplefolder
with content:$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled ='true'";
$wmi.EnableDHCP();
$wmi.SetDNSServerSearchOrder();OR to just change it with a single double-click on the
dynamic_ip.ps1
script:#18-07-20 Todo: add wifi network detection that automatically triggers setting a static IP and back dynamic IP.
# First ensure the script is automatically ran as administrator, else it appearently does not have the privileges to change the local IP adress:
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}
# Next set it dynamic:
$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled ='true'";
$wmi.EnableDHCP();
$wmi.SetDNSServerSearchOrder();
# Now close the window this has just created.
# This leaves other Powershell windows open if they were already open before you ran this script.
# Also, It yields an error with a $ sign at the start of the line.
# Source: https://stackoverflow.com/questions/14874619/powershell-exit-doesnt-really-exit
Stop-Process -Id $PIDIn powershell:
cd c:/example_folder
.\dynamic_ip.ps1
After you have tried it out the first time in powershell succesfully, you can simply set a static IP adress by opening/running the script by opening it with powershell (In explorer, double click the file, or right mouse button (rmb)>open with powershell
). But for this to work, the path to the scripts cannot contain any spaces!
Additional notes:
Do not forget to make the IP adress dynamic again if you leave your home network again, otherwise you can get a problem when you try to access the internet in other wifi/ethernet networks!
your_static_ip_adress
: you can read your dynamic ip adress and routers ip adress by:start>type cmd>open command prompt>type: ipconfig
, or type:ipconfig -all
.* Furthermore, the rules described in the note above, generally apply.your_routers_ip_adress
see "your_static_ip_adress", usually ends with a.1
your_subnetmask
see "your_static_ip_adress"your_dns
, this can be your routers ip adress, or for example googles DNS8.8.8.8
.Rules to determine the static IP adres:
Source:
https://www.howtogeek.com/184310/ask-htg-should-i-be-setting-static-ip-addresses-on-my-router/3.1 Do not assign an address that ends in .0 or .255 as these addresses are typically reserved for network protocols.
3.2 Do not assign an address to the very start of the IP pool, e.g. 10.0.0.1 as the start address is always reserved for the router. Even if you’ve changed the IP address of your router for security purposes, we’d still suggest against assigning a computer.
3.3 Do not assign an address outside of the total available pool of private IP addresses. This means if your router’s pool is 10.0.0.0 through 10.255.255.255 every IP you assign (keeping in mind the prior two rules) should fall within that range.
This is the (semi) automated equivalent of manually filling in the data of the first figure of this post, in order to set a static IP.
(Wifi connection issues troubleshoot) If:
- you have 2 different wifi networks (
A
andB
) to which you can both connect at the same location - where only
B
has the right"your_routers_ip_adress"/local gateway-adress
- And you accidentally set your
local IP
to (the wrong)static IP
whilst connect to the wrong wifi (A
), - Then disconnected the wrong wifi (
A
) before setting thelocal IP
adress to dynamic again, and (as a consequence) experience wifi troubles: (keeps
scanning network requirements
).Then either:
set the
local IP
adress todynamic
.- Reconnect to the wrong wifi network (
A
). - Set it back to
static
, and todynamic
again. - Disconnect from wifi (
A
). Now you should be able to connect to both wifi networks correct again.
Or:
set the
local IP
adress tostatic
.- Reconnect to the wrong wifi network (
A
). - Set it back to
static
, and todynamic
again. - Disconnect from wifi (
A
). - Now you should be able to connect to both wifi networks correct again.
- you have 2 different wifi networks (
Set from static IP to DHCP on Windows 8 using command line
netsh interface ipv4 set address name="Wired Ethernet Connection" source=dhcp
ipconfig /renew Wired*
If above ipconfig /renew
command does not help, try
netsh interface set interface name="Wired Ethernet Connection" admin=DISABLED
netsh interface ipv4 set address name="Wired Ethernet Connection" source=dhcp
netsh interface set interface name="Wired Ethernet Connection" admin=ENABLED
However, maybe all address
, mask
and gateway
obtained from dhcp
could match those defined by source=static
previously.
Are there Lease Obtained
and Lease Expires
properties displayed in the ipconfig /ALL
output?
Getting interfaces and their DNS servers that are STATIC (not dhcp allocated)
I thought this might be available in the System.Net.NetworkInformation
namespace, but evidently not. I looked through a few lower-level Windows networking APIs thinking certainly it must exist somewhere in there, but no such luck. After running dumpbin
on netsh.exe
to see what kinds of libraries/functions it's consuming, I did get an idea of one other place to look: the registry.
As it happens, if you look in the registry under the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\
key you will see a key for each network interface with the name in GUID format. Within an interface's key you will find two values of interest: DhcpNameServer
and NameServer
. On my client system where the DNS server is set by DHCP, DhcpNameServer
contains that DNS server's IP address and NameServer
contains an empty [String]
. If I manually set a DNS server while keeping the automatically-assigned address for the interface itself, NameServer
then contains that manually-set DNS server address while DhcpNameServer
still contains the same DNS server specified by DHCP.
Based on these observations, it would seem that...
- The
DhcpNameServer
value always contains the DNS server(s) specified by DHCP. - The
NameServer
value always contains the DNS server(s) specified manually. - When you query the system for its nameservers (e.g. via the
Win32_NetworkAdapterConfiguration.DNSServerSearchOrder
property) the result will contain the value ofNameServer
, if provided, otherwise the value ofDhcpNameServer
, if provided. In other words, the system tells you which DNS servers are currently being used, but not how their addresses were specified. - To determine if an interface has manually-assigned DNS servers, check if
NameServer
has a non-empty value.
Thus, given an interface with ID $interfaceID
, you can build a path to its registry key like this...
$interfaceKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\$interfaceID"
...and then retrieve the dynamically-assigned and manually-assigned nameserver values like this...
Get-ItemProperty -Path $interfaceKeyPath -Name 'DhcpNameServer', 'NameServer'
That just leaves the matter of from where you get the value for $interfaceID
, and there are numerous sources although the trick will be excluding undesirable interfaces (for example, on my Windows 10 system I have a packet capture loopback adapter and a hypervisor adapter that I'd want to be excluded from such a query). The most compatible way (dating back to .NET 2.0) would be the Id
property of the NetworkInterface
class...
[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() `
| Select-Object -ExpandProperty 'Id'
...although the only useful properties on which to filter are Name
and NetworkInterfaceType
.
On Windows Vista and above the Win32_NetworkAdapter
class provides a GUID
property...
Get-WmiObject -Class 'Win32_NetworkAdapter' -Property 'GUID' -Filter 'PhysicalAdapter = true'
...although even when filtering on PhysicalAdapter
it still returns the loopback and hypervisor adapters and I'm not seeing any definitive property or class relation that can be used to select only hardware adapters.
The Win32_NetworkAdapterConfiguration
class is much the same...
Get-WmiObject -Class 'Win32_NetworkAdapterConfiguration' -Property 'SettingID'
...with no properties to filter out non-hardware or even non-physical adapters.
On (I think) Windows 8 and above there's the Get-NetConnectionProfile
cmdlet...
Get-NetConnectionProfile | Select-Object -ExpandProperty 'InstanceID'
which is documented to get "a connection profile associated with one or more physical network adapters" and, on my system, it does only return my physical adapter.
There is also the Get-NetAdapter
cmdlet...
Get-NetAdapter -Physical `
| Where-Object -Property 'EndPointInterface' -NE -Value $true `
| Select-Object -ExpandProperty 'InterfaceGuid'
I found that passing the -Physical
parameter excluded the hypervisor adapter but not the loopback adapter, so filtering out where EndPointInterface
is $true
was necessary to eliminate that. The HardwareInterface
and Virtual
properties might also be of interest.
Another option would be to invoke the Get-NetAdapterHardwareInfo
cmdlet, which seems to know how to distinguish true hardware adapters, and let that determine which adapters are retrieved by Get-NetAdapter
...
Get-NetAdapterHardwareInfo `
| Get-NetAdapter `
| Select-Object -ExpandProperty 'InterfaceGuid'
The Get-Net*
cmdlets above return CIM instances so, for example, instead of Get-NetAdapter -Physical
you could use something like...
Get-WmiObject -Namespace 'Root\StandardCimv2' -Class 'MSFT_NetAdapter' `
-Property 'InterfaceGuid' -Filter 'HardwareInterface = true AND EndPointInterface = false'
to retrieve the MSFT_NetAdapter
instances just the same. I'm not really sure what the guidance is on using one versus the other. It would seem like one should prefer the cmdlets, and yet, unlike WMI/CIM, they offer limited/no parameters for efficiently filtering the output or specifying which properties are desired so you have to do that in the pipeline. I think it's noteworthy, though, that I wasn't able to find any current documentation for these MSFT_*
class; they all say they're no longer updated, except for the MSFT_NetConnectionProfile
class for which I couldn't find any documentation page at all. That says to me Microsoft doesn't want you relying on any definite structure of these classes, and yet if the cmdlets just pass along those class instances...I'm not sure how can you meaningfully and reliably interact with them if nothing is documented.
Also, keep in mind that you'll want to prefer Get-CimInstance
and its ilk over Get-WmiObject
, where possible. I don't think I've yet encountered an instance where it was any more complicated than changing Get-WmiObject
to Get-CimInstance
, although there are more differences (not necessarily bad) than the name.
Related Topics
Linux Assembly: How to Call Syscall
Calculate Word Occurrences from File in Bash
Comparison of Integer and Floating Point Numbers in Shell Script
Stack Resident Buffer Overflow on 64-Bit
Cmake Include_Directories Order After/Before
Codeigniter Url Rewriting .Htaccess Is Not Working on Centos
What Are the Possible List of Linux Bash Shell Injection Commands
Run Command After 1 Hour in Linux
/Tmp VS. /Dev/Shm for Temp File Storage on Linux
Sed Command:How to Replace If Exists Else Just Insert
Installing Docker on Centos 6.6
How to Extract Text from a Psd File
Shell Variable Issue When Trying to Mkdir
How to Make Awk Use the Variable Created in Bash Script
Kill a Java Process (In Linux) by Process Name Instead of Pid