C#获取主机IP地址:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.Net;
- using System.Collections;
- namespace test
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- this.label1.Text=MyHostIP();
- }
- //获得主机IP地址
- public string MyHostIP()
- {
- // 显示主机名
- string hostname = Dns.GetHostName();
- // 显示每个IP地址
- IPHostEntry hostent = Dns.GetHostEntry(hostname); // 主机信息
- Array addrs = hostent.AddressList; // IP地址数组
- IEnumerator it = addrs.GetEnumerator(); // 迭代器,添加名命空间using System.Collections;
- // 循环到下一个IP 地址
- while (it.MoveNext())
- {
- IPAddress ip = (IPAddress)it.Current; //获得IP地址,添加名命空间using System.Net;
- return ip.ToString();
- }
- return "";
- }
- }
- }