Skip to main content
 首页 » 编程设计

c#之使用 DynDNS 和 WebRequest C# 获取公共(public) IP

2024年01月02日39落叶无声

我使用此代码获取公共(public) IP 地址(感谢这篇文章 How to get the IP address of the server on which my C# application is running on?):

    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 中运行此函数的问题,因此当前用户请求不可用,而是使用服务器上下文?

请帮忙!

请您参考如下方法:

由于您是从服务器发出请求,因此您将获得服务器的 IP 地址。

我不确定你们有什么样的服务。对于 WCF 服务,您可以从请求的 OperationContext 对象的 IncomingMessageProperties 中获取 IP 地址。请在此处查看示例: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); 
    } 
}