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;
namespace IPTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        private void Form1_Click(object sender, EventArgs e)
        {
            
                string host = Dns.GetHostName();
                this.textBox1.Text = host;
                IPHostEntry ipHostEntry = Dns.GetHostEntry(host);
                IPAddress[] addr = ipHostEntry.AddressList;
                this.textBox2.Text = addr[0].ToString();
               
        }
    }
}           我是放了两个Label控件,两个TextBox控件,1个Button控件在窗体上,用作主机名和ip地址的输出,运行之后也没错误,可是点击button之后两个TextBox里面一点反应都没有,好像是引发了System.Net.Sockets.SocketException,请问该怎么改。

解决方案 »

  1.   

    private void Form1_Click(object sender, EventArgs e)
    看你上在函数名,好象是窗体单击事件?
      

  2.   

    测试了一下,使用正常。你用ipconfig确认已经有IP?
      

  3.   

    晕,如1楼所说,应该放在按钮的事件里面        private void button1_Click(object sender, EventArgs e)
            {
                string host = Dns.GetHostName();
                this.textBox1.Text = host;
                IPHostEntry ipHostEntry = Dns.GetHostEntry(host);
                IPAddress[] addr = ipHostEntry.AddressList;
                this.textBox2.Text = addr[0].ToString();
            }
      

  4.   


      我后来改了,textbox里出现了ip地址fe80::856c:e082:d837:5431%11,这是怎么回事。
      

  5.   


    那怎么让他显示ipv4的地址呢
      

  6.   

    示例代码;
       /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string myIP;
            System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
            myIP = addressList[0].ToString();
            return myIP;
        }
      

  7.   

     Form1_Click
    窗体的单机事件,放在里按钮吧
      

  8.   

     Dns.GetHostAddress()? 返回的是一个ip数组!