Asp.net通过IP地址获得域名信息
时间:2011-03-23 来源:苍马之子
本段代码可以获取本机的IP地址,并可以根据IP地址获取本机所在域域名:
.aspx代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
<style type="text/css">
.style1
{
width: 600px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:center;">
<table class="style1">
<tr>
<td colspan="2" style="text-align:center;">
<font face="宋体">
<asp:Label id="Label1"
runat="server">通过域名获得IP地址</asp:Label></font>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<font face="宋体">
<asp:TextBox id="TextBox1" runat="server"
Width="248px"></asp:TextBox>
</font>
</td>
</tr>
<tr>
<td style="text-align:center;">
<font face="宋体">
<asp:Button id="TOIP" runat="server" Text="转化为IP" onclick="TOIP_Click"></asp:Button>
</font>
</td>
<td style="text-align:center;">
<font face="宋体">
<asp:Button id="TOAD" runat="server"
Text="转化为域名" onclick="TOAD_Click"></asp:Button>
</font>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<font face="宋体">
<asp:Label id="Label2" runat="server"></asp:Label>
</font>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
.aspx.cs代码
1 using System;2 using System.Configuration;
3 using System.Data;
4 using System.Linq;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.HtmlControls;
9 using System.Web.UI.WebControls;
10 using System.Web.UI.WebControls.WebParts;
11 using System.Xml.Linq;
12 using System.Net;
13
14 public partial class _Default : System.Web.UI.Page
15 {
16 protected void Page_Load(object sender, EventArgs e)
17 {
18 // 在此处放置用户代码以初始化页面
19 // Dns dns;
20 string hostname = Dns.GetHostName();
21 IPAddress[] ip = Dns.Resolve(hostname).AddressList;
22 Label2.Text = "机器名称:" + hostname.ToString() + "<br>IP地址:" + ip[0].ToString();
23
24 }
25
26 //转化为IP地址
27 protected void TOIP_Click(object sender, EventArgs e)
28 {
29 IPHostEntry hostInfo = Dns.GetHostByName(TextBox1.Text);
30 Label2.Text = hostInfo.AddressList[0].ToString();
31 TextBox1.Text = hostInfo.AddressList[0].ToString();
32
33 }
34
35 //转化为域名
36 protected void TOAD_Click(object sender, EventArgs e)
37 {
38 if(this.TextBox1.Text!="")
39 {
40 IPHostEntry hostInfo = Dns.GetHostByAddress(TextBox1.Text);
41 Label2.Text = hostInfo.HostName;
42 }
43 else
44 {
45 Response.Write("<script> alert('请指定IP地址')</script>");
46 }
47 }
48 }
相关阅读 更多 +