C#中如何獲取IP地址?,看到問題的時(shí)候我也很糾結(jié),糾結(jié)的不是這個(gè)問題是如何的難回答,而是糾結(jié)的是這些問題都是比較基本的常識(shí),也是大家會(huì)經(jīng)常用到的。但是卻不斷的有人問起,追根究底的原因估計(jì)就是沒有好好的總結(jié)。
為了幫助大家能盡快的掌握這些基礎(chǔ)知識(shí),特別在網(wǎng)上搜索了各種解決這個(gè)問題的方法。同時(shí)I也希望大家以后在開發(fā)代碼的過程中能夠?qū)W會(huì)總結(jié)為什么在不同的ip查詢網(wǎng)站上顯示的本機(jī)ip不一樣?,學(xué)會(huì)把基礎(chǔ)知識(shí)鬧鬧把握。
先看看IP地址都有哪些分類:
1、本地機(jī)器IP地址為什么在不同的ip查詢網(wǎng)站上顯示的本機(jī)ip不一樣?,指當(dāng)前設(shè)備的網(wǎng)絡(luò)IP
2、當(dāng)前頁面的IP(Web客戶端),指訪問網(wǎng)站頁面的客戶端ip,一般用于網(wǎng)站監(jiān)控、維護(hù)
3、用戶IP(客戶端),指訪問客戶端的終端ip地址
源碼整理如下:
using System.Net;
using System;
using System.Web;
namespace MarcoPro
{
///
/// 共用工具類
///
public static class IpHelper
{
#region 獲得用戶IP
///
/// 獲得用戶IP

///
public static string GetUserIp()
{
string ip;
string[] temp;
bool isErr = false;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"] == null)
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
else
ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"].ToString();
if (ip.Length > 15)
isErr = true;
else
{
temp = ip.Split('.');
if (temp.Length == 4)
{
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].Length > 3) isErr = true;

}
}
else
isErr = true;
}
if (isErr)
return "1.1.1.1";
else
return ip;
}
#endregion
#region 獲得當(dāng)前頁面客戶端的IP
///
/// 獲得當(dāng)前頁面客戶端的IP
///
/// 當(dāng)前頁面客戶端的IP
public static string GetIP()
{

string result = String.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.UserHostAddress;
}
if (null == result || result == String.Empty || !IsIP(result))
{
return "0.0.0.0";
}
return result;
}
#endregion

///
/// 是否為ip
///
///
///
private static bool IsIP(string ip)
{
return System.Text.RegularExpressions.Regex.IsMatch(ip,
@"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
///
/// 獲取本地機(jī)器IP地址
///
///
public static string GetLocalIP()
{
string strHostIP = string.Empty;
IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName);
if (oIPHost.AddressList.Length > 0)

{
strHostIP = oIPHost.AddressList[0].ToString();
}
return strHostIP;
}
#region 把IP地址轉(zhuǎn)換為數(shù)字格式
///
/// 把IP地址轉(zhuǎn)換為數(shù)字格式
///
/// IP地址
/// 數(shù)字
public static int IPtoNum(string strIp)
{
string[] temp = strIp.Split('.');
return (int.Parse(temp[0])) * 256 * 256 * 256 + (int.Parse(temp[1])) * 256 * 256 * 256 + (int.Parse(temp[2])) * 256 * 256 * 256;
}
#endregion
}
}