C# 获得本机IP、端口等信息地址以及服务器IP信息

 

大概是这样子,代码也没多少,直接上代码了。。

引入命名空间:

 

   using System.Net; 

    namespace IPExample  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
            }  
      
            /// <summary>  
            /// 获得本机IP信息  
            /// </summary>  
            /// <param name="sender"></param>  
            /// <param name="e"></param>  
            private void btn_ShowHostIPInfo_Click(object sender, EventArgs e)  
            {  
                lst_HostIPInfo.Items.Clear();  
                string name = Dns.GetHostName();  
                lst_HostIPInfo.Items.Add("本机主机名:"+name);  
                IPHostEntry me = Dns.GetHostEntry(name);  
                lst_HostIPInfo.Items.Add("本机所有IP地址:");  
                foreach (IPAddress ip in me.AddressList)  
                {  
                    lst_HostIPInfo.Items.Add(ip);  
                }  
                IPAddress localIp = IPAddress.Parse("127.0.0.1");  
                IPEndPoint iep = new IPEndPoint(localIp, 80);  
                lst_HostIPInfo.Items.Add("IP端点:" + iep.ToString());  
                lst_HostIPInfo.Items.Add("IP端口:" + iep.Port);  
                lst_HostIPInfo.Items.Add("IP地址:" + iep.Address);  
                lst_HostIPInfo.Items.Add("IP地址族:" + iep.AddressFamily);  
                lst_HostIPInfo.Items.Add("可分配端口最大值:" + IPEndPoint.MaxPort);  
                lst_HostIPInfo.Items.Add("可分配端口最小值:" + IPEndPoint.MinPort);  
            }  
      
      
            /// <summary>  
            /// 获得服务器信息  
            /// </summary>  
            /// <param name="sender"></param>  
            /// <param name="e"></param>  
            private void btn_ShowServerInfo_Click(object sender, EventArgs e)  
            {  
                lst_ServerIPInfo.Items.Clear();  
                IPHostEntry remoteHost = Dns.GetHostEntry(txt_ServerIPAddress.Text);  
                IPAddress[] remoteIp = remoteHost.AddressList;  
                IPEndPoint iep;  
                foreach (IPAddress ip in remoteIp)  
                {  
                    iep = new IPEndPoint(ip, 80);  
                    lst_ServerIPInfo.Items.Add(iep);  
                }  
            }  
      
      
        }  
    }  

 

posted @ 2018-01-04 09:45  三人成虎  阅读(4007)  评论(0编辑  收藏  举报