[VB.NET]获得主机名和IP地址

来源:互联网 发布:通州淘宝城关了吗 编辑:程序博客网 时间:2024/05/18 03:48
获得主机名和IP地址

实例说明

在本实例中,我们将制作一个能获得计算机名称和本地IP地址的应用程序。程序运行后,可以点击"更改主机名"按钮,在弹出的对话框中输入要修改的名称,确定后重新启动计算机即可实现改变。程序运行结果如图79-1所示。

<script type="text/javascript"><!--google_ad_client = "pub-8333940862668978";/* 728x90, 创建于 08-11-30 */google_ad_slot = "4485230109";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

图79-1 运行结果

技术要点

l 获得/更改计算机名称

l 获得本地IP地址

实现过程

■ 新建项目

打开Visual Studio.NET,选择"新建项目",在项目类型窗口中选择"Visual Basic项目",在模板窗口中选择"Windows应用程序",在名称域中输入"GetComputerIP",然后选择保存路径。单击"确认"。

■ 添加控件

向当前窗体上添加四个Label控件,一个Button控件和一个AxWinSocket控件(AxWinSocket控件需要从自定义工具箱中添加,此控件不属于标准控件,添加方法请见前面实例)。

■ 设置属性

将Button控件和两个Label控件的Text属性改为和界面一致即可。

■ 添加代码

Public Sub New()

MyBase.New()

'This call is required by the Windows Form Designer.

InitializeComponent()

' 得到计算机名称还可以使用GetComputerName()API函数

Label2.Text = UCase(AxWinsock1.LocalHostName)

' 得到本机的IP地址

Label4.Text = AxWinsock1.LocalIP

End Sub

Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long

Private Declare Function SetComputerName Lib "kernel32" Alias "SetComputerNameA" (ByVal lpComputerName As String) As Long

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim chgcompuname As String, res As Long

chgcompuname = InputBox("请输入您的计算机的名称", "更改计算机名")

' 设置新的计算机名

res = SetComputerName(chgcompuname)

If res <> 0 Then

Label2.Text = UCase(chgcompuname)

MsgBox("下次启动计算机更改将生效")

End If

End Sub

■ 运行程序

单击菜单"调试|启动"或单击 图标运行程序。

小结

在本实例中,我们通过使用winsock控件制作出了在开发程序中经常使用到的程序,即可以得到本地的计算机名称和IP地址的程序。