如何获取远程客户端IP地址并存储在表中 [英] How to get remote client ip address and store in a table
问题描述
我实际上想要获取访问我网站并存储在sql表中的客户端的IP地址。我尝试在页面加载中使用以下代码,但给出错误说明:
'由于'getipaddress_test.Page_Load(object,System.EventArgs)'返回void,因此返回关键字后面不能包含对象表达'。
I actually want to get the ip addresses of those clients who visit my website and store in a sql table. I attempted with the following code in page-load but gives error stating :
'Since 'getipaddress_test.Page_Load(object, System.EventArgs)' returns void, a return keyword must not be followed by an object expression'.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Net;
using System.Web.UI.WebControls;
public partial class getipaddress_test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipList))
{
return ipList.Split(',')[0];
}
return Request.ServerVariables["REMOTE_ADDR"];
}
}
有人可以指导我吗?
Can anyone guide me out?
推荐答案
看看这个
Have a look at this
string ip = Server.HtmlEncode(Request.UserHostAddress);
这将为您提供ip作为字符串。您可以随时随地将其插入数据库。
注意:
如果你从localhost运行它,你每次都会得到127.0.0.1。
问候......:笑:
This will give you ip as a string. You can insert it into database wherever you want.
Note:
You will get 127.0.0.1 every time if you run it from localhost.
Regards..:laugh:
认真地?我的意思是抛弃所有的实现,我宁愿建议你回到基础并阅读C#(或任何其他语言)的书。
来自MSDN:
当用作方法的返回类型时,void指定该方法不返回值。
http://msdn.microsoft.com /en-us/library/system.void.aspx [ ^ ]
您的代码应如下所示:
Seriously? I mean leave all the implementation aside, I would rather recommend you to go back to basics and read a C# (or any other language for that matter) book.
From MSDN:
When used as the return type for a method, void specifies that the method doesn't return a value.
http://msdn.microsoft.com/en-us/library/system.void.aspx[^]
Your code should look something like this:
protected void Page_Load(object sender, EventArgs e)
{
string ipAddress = GetIPAddress();
//Store this IPAddress into table
}
private string GetIPAddress()
{
string ipAddress = string.Empty;
//get client IP Address
return ipAddress;
}
这篇关于如何获取远程客户端IP地址并存储在表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!