如何以编程方式自动获取IP地址

时间:2013-12-04 11:09:42

标签: vb.net ip wmi ip-address

Dim args As String
args="netsh wlan interface ip set address """+adptrname+""" dhcp"
Dim proc As New System.Diagnostics.Process()        
proc.StartInfo.FileName = "netsh"
proc.StartInfo.Verb="RunAs"
proc.StartInfo.CreateNoWindow = true
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.Arguments = args
proc.StartInfo.UseShellExecute = False
proc.Start()
My.Computer.FileSystem.WriteAllText(MainForm.filePath,proc.StandardOutput.ReadToEnd(), True)
proc.Close()
MsgBox(args)

我写了上面的代码来改变我的wlan适配器以自动获取IP地址,但它仍然保留在旧的ip配置上,尽管输出说dhcp已启用。有人可以告诉我哪里出错了。

1 个答案:

答案 0 :(得分:2)

好的我试着在评论中这样做,但我一直在寻找错误......所以这里是你的代码的更正版本:

'Where does your adptrname come from?
Dim adptrname As String = "wlan0" 'i.E.

Dim args As String
' Note that i removed 'netsh' from args
' And the notation to add the addapter name (in VB we use & instead of +)
args="netsh int ipv4 set address name=""" & adptrname & """ source=dhcp"
Dim proc As New System.Diagnostics.Process()        
proc.StartInfo.FileName = "netsh"
proc.StartInfo.Verb="RunAs"
proc.StartInfo.CreateNoWindow = true
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.RedirectStandardError = True ' maybe you want to read this, too
proc.StartInfo.Arguments = args
proc.StartInfo.UseShellExecute = False
proc.Start()

' This is still bad, but we keep it for now
My.Computer.FileSystem.WriteAllText(MainForm.filePath, proc.StandardOutput.ReadToEnd(), True)
My.Computer.FileSystem.WriteAllText(MainForm.filePath, proc.StandardError.ReadToEnd(), True)


' Normally not necessery, but no way we do proc.close() here
proc.WaitForExit()

' ok, this shoud have shown you until now that it didn't work...
MsgBox(args)

阅读评论,尝试对您自己的代码进行更正,看看它是否正常运行。

编辑参数

我也在想它不会与你的论点合作......

请尝试这样:

netsh int ipv4 set address name="Wireless Connection" source=dhcp

我是从帮助中构建的,它可以在我的机器上运行(Win7x64-en_US)