Setting up static DNS and Alternate DNS server programmatically? - vb.net

I found this code as i search on google. I just want to change my DNS server to static. I just dont know where to put my static DNS and Alternate Dns Servers here. Please help me. Thanks :)
Public Sub setDNS(ByVal NIC As String, ByVal DNS As String)
Dim objMC As New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If CBool(objMO("IPEnabled")) Then
' if you are using the System.Net.NetworkInformation.NetworkInterface you'll need to change this line to if (objMO["Caption"].ToString().Contains(NIC)) and pass in the Description property instead of the name
If objMO("Caption").Equals(NIC) Then
Try
Dim newDNS As ManagementBaseObject = objMO.GetMethodParameters("SetDNSServerSearchOrder")
newDNS("DNSServerSearchOrder") = DNS.Split(","c)
Dim setDNS As ManagementBaseObject = objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, Nothing)
Catch generatedExceptionName As Exception
Throw
End Try
End If
End If
Next
End Sub
Any HELP would be so much appreciated. Thanks in advance.

Related

How to solve duplicate static IP between network adapter in VB?

I have a program so user can switch and apply network configuration based on profile.
Public Shared Sub SetIP(ByVal nicName As String, ByVal IpAddresses As String, ByVal SubnetMask As String, ByVal gateway As String, ByVal dnsSearch1 As String, ByVal dnsSearch2 As String)
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
'Dim objMO As ManagementObject
For Each objMO As ManagementObject In objMOC
'Make sure this is enabled device. Not VMWare or memory card
If objMO("IPEnabled") Then
If (objMO("Caption").Equals(nicName)) Then
Dim objNewIP As ManagementBaseObject = objMO.GetMethodParameters("EnableStatic")
Dim objNewGate As ManagementBaseObject = objMO.GetMethodParameters("SetGateways")
Dim objNewDns As ManagementBaseObject = objMO.GetMethodParameters("SetDNSServerSearchOrder")
'Set DefaultGateway
objNewGate("DefaultIPGateway") = New String() {gateway}
objNewGate("GatewayCostMetric") = New Integer() {1}
'Set IPAddress and Subnet Mask
objNewIP("IPAddress") = IpAddresses.Split(","c) 'major changes
objNewIP("SubnetMask") = New String() {SubnetMask}
'Set DNS for only preferred
'objNewDns("DNSServerSearchOrder") = dnsSearch1.Split(","c)
'Dim setDns = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDns, Nothing) 'comment jap
'try to set alternate here
Dim dns() As String = {dnsSearch1, dnsSearch2}
objNewDns("DNSServerSearchOrder") = dns
Dim setIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
Dim setGateways = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)
objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDns, Nothing)
Exit For
End If
End If
Next
End Sub
By using WMI classes, right now WIFI adapter already set with 172.25.35.12 static IP address, and user want to switch to Ethernet which also will be using the same IP address.
After set with that IP, it will cause conflict where WIFI adapter is disabled. How can I solve the issues? Maybe I need to reset WIFI IP configuration at first..

Sending Files over IpV6

I want to send a file over the internet with a tcp connection. My code handles this for IpV4 well (creddits here go to http://technotif.com/creating-simple-tcpip-server-client-transfer-data-using-c-vb-net/, i just changed minor things to correct the file output)
I tried to use this with a friend of mine, but his router is uteer garbage, and it cant forward any ports whatsoever and wont even work with upnp. It is set to IpV6 as well, and as far as I know IPv6 doesnt need anymore port forwarding since every device has its own public ip.
sadly my program doesnt work with IPv6 adresses, and I have a hard time finding any information regarding this topic.
Here is my code:
Public Class Form1
Private nSockets As ArrayList
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim IPHost As IPHostEntry
IPHost = Dns.GetHostByName(Dns.GetHostName())
lblStatus.Text = "My IP address is " +
IPHost.AddressList(0).ToString()
nSockets = New ArrayList()
Dim thdListener As New Thread(New ThreadStart _
(AddressOf listenerThread))
thdListener.Start()
End Sub
Public Sub listenerThread()
Control.CheckForIllegalCrossThreadCalls = False
Dim tcpListener As New TcpListener(7080)
Dim handlerSocket As Socket
Dim thdstHandler As ThreadStart
Dim thdHandler As Thread
tcpListener.Start()
Do
handlerSocket = tcpListener.AcceptSocket()
If handlerSocket.Connected Then
lbConnections.Items.Add(
handlerSocket.RemoteEndPoint.ToString() +
"connected.")
SyncLock (Me)
nSockets.Add(handlerSocket)
End SyncLock
thdstHandler = New ThreadStart(AddressOf _
handlerThread)
thdHandler = New Thread(thdstHandler)
thdHandler.Start()
End If
Loop
End Sub
Public Sub handlerThread()
Dim handlerSocket As Socket
handlerSocket = nSockets(nSockets.Count - 1)
Dim networkStream As NetworkStream = New _
NetworkStream(handlerSocket)
Dim blockSize As Int16 = 16
Dim thisRead As Int16
Dim dataByte(blockSize) As Byte
SyncLock Me
' Only one process can access the
' same file at any given time
Dim fileStream As Stream
fileStream = File.OpenWrite("C:\Whatever.file")
While (True)
thisRead = networkStream.Read(dataByte,
0, dataByte.Length)
fileStream.Write(dataByte, 0, thisRead)
If thisRead = 0 Then Exit While
End While
fileStream.Close()
networkStream.Close()
End SyncLock
lbConnections.Items.Add("File Written")
handlerSocket = Nothing
End Sub
How do i make it IPv6 capable?
Forgot to put in my client, what do i have to change here to make it work? Since even with the changes to my server, its still not connecting properly.
Private Sub Sendfile()
Dim filebuffer As Byte()
Dim fileStream As Stream
fileStream = File.OpenRead(tbFilename.Text)
' Alocate memory space for the file
ReDim filebuffer(fileStream.Length)
fileStream.Read(filebuffer, 0, fileStream.Length)
' Open a TCP/IP Connection and send the data
Dim clientSocket As New TcpClient(tbServer.Text, 7080)
Dim networkStream As NetworkStream
networkStream = clientSocket.GetStream()
networkStream.Write(filebuffer, 0, fileStream.Length)
networkStream.Close()
End Sub
Your listener is currently listening to IPv4-address 0.0.0.0, which is the default when you only specify a port to the listener.
You need to use the TcpListener(IPAddress, Integer) overload and specify IPv6Any to listen to IPv6-addresses.
Dim tcpListener As New TcpListener(IPAddress.IPv6Any, 7080)
As a side note you should rather use a List(Of T) than an ArrayList. The latter is typeless and not as optimized for .NET as the former.

Blocking more folders and applications

As you can see here I block the directory called "cleo". If I have it in my folder I can't click connect. How can I check if, for example, "Cleo", "Images", "Logs" exist in browsed file. I don't think making multiple If statements would be good, is there any other way?
Private Sub connect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connect.Click
Dim cleoPath As String
Dim filePath As String
filePath = System.IO.Path.Combine(TextBox2.Text, "gta_sa.exe")
cleoPath = System.IO.Path.Combine(TextBox2.Text, "cleo")
If File.Exists(filePath) Then
If Directory.Exists(cleoPath) Then
MsgBox("Pronasli smo cleo fajl u vasem GTA root folderu. Da se konektujete na server morate ga obrisati.")
Else
Dim p() As Process
p = Process.GetProcessesByName("samp")
If p.Count > 0 Then
MsgBox("Vec imate pokrenut SAMP - ugasite ga.")
Else
Try
Dim prozess As Process = Process.GetProcessesByName("samp")(0)
prozess.Kill()
Catch ex As Exception
End Try
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SAMP", "PlayerName", TextBox1.Text)
Process.Start("samp://193.192.58.55:7782")
Dim client As New TcpClient
client.Connect("193.192.58.55", 10924)
Dim sendbytes() As Byte = System.Text.Encoding.ASCII.GetBytes(TextBox1.Text)
Dim stream As NetworkStream = client.GetStream()
stream.Write(sendbytes, 0, sendbytes.Length)
End If
End If
Else
MsgBox("Da se konektujete morate locirati GTA San Andreas folder.")
End If
End Sub
End Class
You could use extension methods combined with a directoryinfo to check if any of a list of directory exists. Depending of if you just want a true/false return or if you need to process each directories (for instance, by adding a custom message with the name of the folders that prevent your application from continuing.
Public Module DirectoryInfoExt
<System.Runtime.CompilerServices.Extension()>
Public Function AnyExists(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As Boolean
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Any(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function GetExistingDirectories(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As IEnumerable(Of String)
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Where(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
End Module
An example the boolean return.
Dim BaseDirectory As String = "C:\Games\GTA"
Dim GamePath As New DirectoryInfo(BaseDirectory)
' Will not give the specific path that exists, only a Boolean if any of theses folder are found
Dim ModsFound As Boolean = GamePath.AnyExists("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
If Not ModsFound Then
'Connect
Else
' Do something
End If
An example using the list return to generate a custome message prompt stating the name of the specific folders found.
'This version gives a list instead.
Dim ModsFoundList As IEnumerable(Of String) = GamePath.GetExistingDirectories("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
Dim HasMod As Boolean = ModsFoundList.Count > 0
If HasMod Then
EvilModdedUserPrompt(ModsFoundList)
Exit Sub
End If
' Here, since HasMod is false, we can proceed with connection.
' Do connection
As for the EvilModdedUserPrompt method
Public Sub EvilModdedUserPrompt(ModsFoundList As List(Of String))
Dim OutputMessage As New Text.StringBuilder
OutputMessage.AppendLine("The following mods have been detected on your system:")
For Each Moditem As String In ModsFoundList
OutputMessage.AppendFormat("- {0}", Moditem)
OutputMessage.AppendLine()
Next
MessageBox.Show(OutputMessage.ToString)
End Sub

Visual Basic - Web Request 403 Forbidden

I am new to Visual Basic so I dont know much about Syntax e.t.c
So if anyone could help me out that be great!
Im getting a 403 Forbidden Error most likely because of the User Agent being used. The website is probably picking up that its not an actual user entering the Website and therefore blocks access.
How do I apply a User Agent that will bypass this issue? I have no idea where to put the Syntax.
My Code:
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sources(1) As String
array(0) = "http://proxy-ip-list.com"
array(1) = "http://sslproxies24.blogspot.com/feeds/posts/default"
For Each element As String In sources
'Connect to the Proxy Source;
Dim source As Net.HttpWebRequest = Net.WebRequest.Create(element)
'Prepare the Response;
Dim response As Net.HttpWebResponse = source.GetResponse
'Load the HTML;
Dim reader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
Dim html As String = reader.ReadToEnd
'Regex;
Dim expression As New Regex("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,4}")
'Set the Matches variable to the Matched Sections of the HTML source;
Dim matches As MatchCollection = expression.Matches(html)
'Add the proxies to the ListBox;
For Each proxy As Match In matches
ListBox1.Items.Add(proxy)
Next
Next
End Sub
End Class

Set IP and DNS to use DHCP from WMI in VB.net

I'm trying to interact with WMI through a vb.net program in order to make any machine that runs this program pull the IP settings and DNS server settings from DHCP for all network adapters with an IP.
The code I presently have works for DHCP without issue, but does not change DNS settings. The program compiles and executes without issue, but the DNS settings are not changing to be fetched automatically from DHCP.
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If (Not CBool(objMO("IPEnabled"))) Then
Continue For
End If
Try
Dim objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewDNS As ManagementBaseObject = Nothing
Dim objSetDNS As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableDHCP")
objSetIP = objMO.InvokeMethod("EnableDHCP", Nothing, Nothing)
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")
objSetDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", Nothing, Nothing)
Catch ex As Exception
MessageBox.Show("Settings unchanged : " & ex.Message)
End Try
Next objMO
I'm so close to getting this solved, I just need help to figure out this last step.
You annoyingly have to do it through the registry, they didn't add WMI methods for it. Specifically (taken from here: https://gallery.technet.microsoft.com/7b1cec46-bdb8-4afc-b240-9789eefce6de) you need to set this key to null.
"HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\"
Below is your code with the necessary new sub inserted in
Const conKeyPath = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
Public Sub Test()
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If (Not CBool(objMO("IPEnabled"))) Then
Continue For
End If
Try
Dim objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewDNS As ManagementBaseObject = Nothing
Dim objSetDNS As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableDHCP")
objSetIP = objMO.InvokeMethod("EnableDHCP", Nothing, Nothing)
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")
objSetDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", Nothing, Nothing)
SetDNSAutomatically(objMO.GetPropertyValue("settingID"))
Catch ex As Exception
MessageBox.Show("Settings unchanged : " & ex.Message)
End Try
Next objMO
End Sub
Private Sub SetDNSAutomatically(ByVal settingID As String)
If settingID = String.Empty Then
Throw New ArgumentNullException("settingID")
End If
Dim _adapterKeyPath = String.Format("{0}\{1}", conKeyPath, settingID)
My.Computer.Registry.SetValue(_adapterKeyPath, "NameServer", String.Empty)
End Sub