天天看點

獲得主機域名及其IP和Port端口

主程式代碼:

   // 由主機域名獲得其IP位址

    protected void btnShowLocal_Click(object sender, EventArgs e)

    {

        txtaShowAnswer.Value = "";

        string strShowAnwser = string.Empty;

        string strHostName = Dns.GetHostName(); //擷取本地主機名

        strShowAnwser = "The local host's name is: " + strHostName + "/n";

        IPHostEntry ipHost = Dns.GetHostEntry(strHostName); //将主機名解析成IPHostEntry執行個體

        foreach (IPAddress ip in ipHost.AddressList) //将主機名(域名)對應的IP全部解析出來

            strShowAnwser += "The local host's IP is: " + ip.ToString() + "/n";

        IPAddress LocalIP = IPAddress.Parse("127.0.0.1"); //将字元串執行個體成IP位址

        IPEndPoint ipEP = new IPEndPoint(LocalIP, 80); //将網絡端點表示成IP位址和端口号

        strShowAnwser += "The IPEndPoint is: " + ipEP.ToString() + "/n";

        strShowAnwser += "The Address is: " + ipEP.Address + "/n";

        strShowAnwser += "The Port is: " + ipEP.Port + "/n";

        strShowAnwser += "The AddressFamily is: " + ipEP.AddressFamily + "/n";

        strShowAnwser += "The Max port number is: " + IPEndPoint.MaxPort + "/n";

        strShowAnwser += "The Min port number is: " + IPEndPoint.MinPort + "/n";

        txtaShowAnswer.Value = strShowAnwser;

    }

運作結果:

The local host's name is: Young

The local host's IP is: ::1

The local host's IP is: 210.77.29.132

The IPEndPoint is: 127.0.0.1:80

The Address is: 127.0.0.1

The Port is: 80

The AddressFamily is: InterNetwork

The Max port number is: 65535

The Min port number is: 0