GetHostAndIP.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetHostAndIP.aspx.cs" Inherits="GetHostAndIP" %>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 925px; height: 180px">
<tr>
<td style="width: 44px">
<asp:TextBox ID="txtDomain" runat="server"></asp:TextBox></td>
<td style="width: 3px">
<asp:Button ID="btnOK" runat="server" Text="轉換為IP位址:" OnClick="btnOK_Click" /></td>
<td style="width: 116px">
&nbsp;<asp:Label ID="lblMsg" runat="server"></asp:Label></td>
</tr>
<td style="width: 44px; height: 76px;">
<asp:TextBox ID="txtIP" runat="server"></asp:TextBox>&nbsp;
</td>
<td style="width: 3px; height: 76px;">
<asp:Button ID="Button1" runat="server" Text="對應域名為:" OnClick="Button1_Click"/></td>
<td style="width: 116px; height: 76px;">
<asp:Label ID="lblDomain" runat="server" Text=""></asp:Label></td>
<td style="width: 44px; height: 30px;">
<td style="width: 3px; height: 30px;">
<td style="width: 116px; height: 30px;">
</table>
</div>
</form>
</body>
</html>
code behind代碼:GetHostAndIP.aspx.cs:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Net;
public partial class GetHostAndIP : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//得到目前浏覽器頭資訊
NameValueCollection headers = new NameValueCollection();
headers = Request.Headers;
string strCookies = null;
for (int i = 0; i < headers.Count; i++)
{
strCookies = headers.GetKey(i);
Response.Write("<br>Name:" + strCookies + "&nbsp;&nbsp;&nbsp;&nbsp;Value:" + headers.Get(strCookies));
}
//得到主機名和IP
string hostName = Dns.GetHostName();
IPAddress[] ip = Dns.GetHostAddresses(hostName);
Response.Write("ServerName :&nbsp" + hostName + "&nbsp;&nbsp;&nbsp;IP:&nbsp&nbsp" + ip[0].ToString());
}
protected void btnOK_Click(object sender, EventArgs e)
IPAddress[] ip = Dns.GetHostAddresses(txtDomain.Text);
lblMsg.Text = ip[0].ToString();
//or
//IPHostEntry hostInfo = Dns.GetHostByName(txtDomain.Text);//gets the DND info for the specified DNS host name
//lblMsg.Text = hostInfo.AddressList[0].ToString();
protected void Button1_Click(object sender, EventArgs e)
IPHostEntry hostInfo = Dns.GetHostEntry(txtIP.Text);
lblDomain.Text = hostInfo.HostName;
}
說明:
IPHostEntry:為 Internet 主機位址資訊提供容器類。
程式中用到的屬性:
AddressList 擷取或設定與主機關聯的 IP 位址清單。
HostName 擷取或設定主機的 DNS 名稱。
Dns靜态類:提供簡單的域名解析功能,它從 Internet 域名系統 (DNS) 檢索關于特定主機的資訊。在 IPHostEntry 類的執行個體中傳回來自 DNS 查詢的主機資訊。如果指定的主機在 DNS 資料庫中有多個入口,則 IPHostEntry 包含多個 IP 位址和别名。
本文轉自 august 51CTO部落格,原文連結:http://blog.51cto.com/august/6970,如需轉載請自行聯系原作者