hosts file modification base on network address

There are times, we might have a different networks and for each one we might need different manual IP and name mapping in “hosts” file.

Let’s assume we have one iSCSI server (iscsi-srv.test.lab) connected to two different networks (192.168.10.x/24 & 192.168.11.x/24) providing service.

For some reason these two network can see each other so if we use “iscsi-srv” as DNS name (iscsi-srv 192.168.10.10 NS 192.168.11.10) and have it with both IP addresses there’s a chance that the name resolution don’t work as we want and the client might use different network (client from network 10 connect to 11.10 or vice versa) and connect to the server making more network traffic.

In this case we might need to add iscsi-srv with related IP for client in each network; few days back I wrote below small PowerShell script to modify “hosts” file on windows system in two different network and I’m sharing it here in case you might want to modify/use it based on your network need as well.

 

# Manually modifying the hosts file for mapping base on the host network

$ip = Get-NetIPAddress | Where {$_.ipaddress -like "192.168.*"}
if ($ip.IPv4Address -like '*.*.10.*') {
  echo Net10
  if (!(Get-Content "C:\Windows\System32\drivers\etc\hosts" | Select-String "iscsi-srv")) {
    $Net10 = "iscsi-srv 192.168.10.10"
    mkdir c:\temp_hosts
    Get-Content "C:\Windows\System32\drivers\etc\hosts" | Out-File c:\temp_hosts\hosts
    $Net10 | Out-File -Append c:\temp_hosts\hosts
    Copy-Item c:\temp_hosts\hosts "C:\Windows\System32\drivers\etc\hosts" -Force
    Remove-Item C:\temp_hosts\hosts -Force
    Remove-Item c:\temp_hosts\ -Force
  } else { echo "host mapping exist" }
} elseif ($ip.IPv4Address -like '*.*.11.*') {
  echo Net11
  if (!(Get-Content "C:\Windows\System32\drivers\etc\hosts" | Select-String "iscsi-srv")) {
    $Net11 = "iscsi-srv 192.168.11.10"
    mkdir c:\temp_hosts
    Get-Content "C:\Windows\System32\drivers\etc\hosts" | Out-File c:\temp_hosts\hosts
    $Net11 | Out-File -Append c:\temp_hosts\hosts
    Copy-Item c:\temp_hosts\hosts "C:\Windows\System32\drivers\etc\hosts" -Force
    Remove-Item C:\temp_hosts\hosts -Force
    Remove-Item c:\temp_hosts\ -Force
  } else { echo "host mapping exist" }
}

It's your kindness to leave a reply/feedback