-->

获取使用DynDNS的和WebRequest的C#公网IP(Get public IP using

2019-09-17 06:06发布

我使用此代码来获取公网IP地址(感谢这个帖子如何获得上我的C#应用程序正在运行的服务器的IP地址? ):

    public static string GetPublicIP()
    {
        try
        {
            String direction = "";
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                {
                    direction = stream.ReadToEnd();
                }
            }

            //Search for the ip in the html
            int first = direction.IndexOf("Address: ") + 9;
            int last = direction.LastIndexOf("</body>");
            direction = direction.Substring(first, last - first);

            return direction;
        }
        catch (Exception ex)
        {
            return "127.0.0.1";
        }
    }

但是,没有谁是访问我的网站的事情,他们都得到了相同的IP,它是服务器公网IP,而不是当前用户的IP。

是否有可能在当前用户的上下文中运行的WebRequest,不作为服务器?

或者是,我跑内部App_Code文件这一功能使当前用户的请求无法使用,而是使用服务器方面的问题?

请帮忙!

Answer 1:

既然你正在从服务器请求您将获得服务器的IP地址。

我不知道你有什么样的服务。 在WCF服务的情况下,你可以抓住从的OperationContext对象请求的IncomingMessageProperties的IP地址。 这里看一个例子: 获取客户端的地址在WCF

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string GetAddressAsString();
}

public class MyService : IMyService
{
    public string GetAddressAsString()
    {
        RemoteEndpointMessageProperty clientEndpoint =
            OperationContext.Current.IncomingMessageProperties[
            RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

        return String.Format(
            "{0}:{1}",
            clientEndpoint.Address, clientEndpoint.Port);
    }
}


Answer 2:

我猜测这个代码是Web服务器上运行 - 你已经有了一个网页,让我们的客户检查他们的IP地址? 如果是的话,我怀疑你有困惑。 如果不是,请详细说明这何处运行。

如果上面的代码服务器上运行,那么你将永远,如果你拨打电话到远程服务器获取服务器的公网IP地址,并问“这是什么发出请求的IP地址” -这是你的代码示例是什么这样做。

如果你想在客户端的IP地址给你打电话-假设你是一个Web应用程序,那么你应该看看HttpWebRequest.UserHostAddress ,altrhough意识到,这并非万无一失。 看看这里获取更多信息。



Answer 3:

这是应该发生的,代码是你的机器上运行,所以你得到你自己的IP地址。 为了从用户那里得到的东西,你必须检查你的用户,特别是REMOTE_ADDR头中发送头。

你或许可以在代码中使用Request.ServerVariables [“REMOTE_ADDR”]某处。



文章来源: Get public IP using DynDNS and WebRequest C#
标签: c# ip dyndns