获取使用DynDNS的和WebRequest的C#公网IP [英] Get public IP using DynDNS and WebRequest C#

查看:239
本文介绍了获取使用DynDNS的和WebRequest的C#公网IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码来获取公网IP地址(感谢这个帖子的如何得到我自己的IP地址在C#):

I Use this code to get the public IP-address (thanks to this post How to get my own IP address in C#?):

    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

But no matter who that access my website, they all get the same IP, and it is the server public IP, not the current user's IP.

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

Is it possible to run the WebRequest in context of the current user, not as the server?

或者是,我运行内部App_Code文件这一功能,使得当前用户请求不可用,而是使用服务器方面的问题?

Or is the problem that I run this function inside App_Code so that the current user Request is not available, instead it use the server context?

请帮帮忙!

推荐答案

既然你正在从服务器的请求,你会获取服务器的IP地址。

Since you are making the request from the server you will get the server's IP address.

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

I am not sure what sort of service you have. In the case of a WCF service, you can grab the IP address from the IncomingMessageProperties of the OperationContext object for the request. See an example here: Get the Client’s Address in 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);
    }
}

这篇关于获取使用DynDNS的和WebRequest的C#公网IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆