本文實例講述了C#編程獲取IP地址的方法。分享給大家供大家參考,具體如下:
1、獲取客戶端IP
/// <summary>/// 獲取客戶端Ip/// </summary>/// <returns></returns>public String GetClientIp(){ String clientIP = ""; if (System.Web.HttpContext.Current != null) { clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(clientIP) || (clientIP.ToLower() == "unknown")) { clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"]; if (string.IsNullOrEmpty(clientIP)) { clientIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } } else { clientIP = clientIP.Split(',')[0]; } } return clientIP;}2、服務器端獲取客戶端請求IP和客戶端機器名稱
/// <summary>/// 服務器端獲取客戶端請求IP和客戶端機器名稱/// </summary>public static void GetClientInfo(){ OperationContext context = OperationContext.Current; MessageProperties messageProperties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; string clientIp = !string.IsNullOrEmpty(requestProperty.Headers["X-Real-IP"]) ? requestProperty.Headers["X-Real-IP"] : endpointProperty.Address; string clientName = Environment.MachineName; Console.WriteLine("ClientIp: " + clientIp + "clientName:" + clientName);}PS:這里再為大家推薦幾款IP相關工具供大家參考使用:
IP地址歸屬地在線查詢工具:
http://tools.VeVB.COm/aideddesign/ipcha
在線IP地址/子網掩碼計算與轉換工具:
http://tools.VeVB.COm/aideddesign/ip_net_calc
在線網絡計算器|TCP/IP子網掩碼計算與換算工具:
http://tools.VeVB.COm/aideddesign/ipcalc
更多關于C#相關內容感興趣的讀者可查看本站專題:《C#程序設計之線程使用技巧總結》、《WinForm控件用法總結》、《C#中XML文件操作技巧匯總》、《C#常見控件用法教程》、《C#數據結構與算法教程》、《C#數組操作技巧總結》及《C#面向對象程序設計入門教程》
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答