C#에서 사용자의 공용 IP 주소를 가져오는 방법
저는 제 웹사이트를 사용하고 있는 고객의 공용 IP 주소를 원합니다.아래 코드는 LAN의 로컬 IP를 보여주고 있지만, 나는 클라이언트의 퍼블릭 IP를 원합니다.
//get mac address
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
}
// To Get IP Address
string IPHost = Dns.GetHostName();
string IP = Dns.GetHostByName(IPHost).AddressList[0].ToString();
출력:
IP 주소: 192.168.1.7
공용 IP 주소를 얻을 수 있도록 도와주세요.
다음을 사용합니다.
protected void GetUser_IP()
{
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
uip.Text = "Your IP is: " + VisitorsIPAddr;
}
"uip"은 사용자 IP를 표시하는 aspx 페이지의 레이블 이름입니다.
"를 사용할 수 있습니다.HTTP_X_FORWARDED_FOR" 또는 "REMOTE_ADDR" 헤더 속성.
방문자 가져오기 방법 참조시스템 구문 블로그의 IP 주소입니다.
/// <summary>
/// method to get Client ip address
/// </summary>
/// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
/// <returns></returns>
public static string GetVisitorIPAddress(bool GetLan = false)
{
string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
{
GetLan = true;
visitorIPAddress = string.Empty;
}
if (GetLan && string.IsNullOrEmpty(visitorIPAddress))
{
//This is for Local(LAN) Connected ID Address
string stringHostName = Dns.GetHostName();
//Get Ip Host Entry
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
//Get Ip Address From The Ip Host Entry Address List
IPAddress[] arrIpAddress = ipHostEntries.AddressList;
try
{
visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
}
catch
{
try
{
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
try
{
arrIpAddress = Dns.GetHostAddresses(stringHostName);
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
visitorIPAddress = "127.0.0.1";
}
}
}
}
return visitorIPAddress;
}
이 모든 제안들과 그 뒤에 있는 이유들의 조합.더 많은 테스트 사례도 자유롭게 추가할 수 있습니다.클라이언트 IP를 가져오는 것이 가장 중요한 경우 이 모든 것을 비교하여 어떤 결과가 더 정확한지 확인할 수 있습니다.
이 스레드에 있는 모든 제안과 내 코드를 간단히 확인할 수 있습니다.
using System.IO;
using System.Net;
public string GetUserIP()
{
string strIP = String.Empty;
HttpRequest httpReq = HttpContext.Current.Request;
//test for non-standard proxy server designations of client's IP
if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
{
strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
}
else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
//test for host address reported by the server
else if
(
//if exists
(httpReq.UserHostAddress.Length != 0)
&&
//and if not localhost IPV6 or localhost name
((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
)
{
strIP = httpReq.UserHostAddress;
}
//finally, if all else fails, get the IP from a web scrape of another server
else
{
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
strIP = sr.ReadToEnd();
}
//scrape ip from the html
int i1 = strIP.IndexOf("Address: ") + 9;
int i2 = strIP.LastIndexOf("</body>");
strIP = strIP.Substring(i1, i2 - i1);
}
return strIP;
}
이 코드는 웹 사이트에 액세스하는 클라이언트의 주소가 아닌 서버의 IP 주소를 가져옵니다.HttpContext를 사용합니다.현재.요청합니다.클라이언트의 IP 주소에 대한 UserHostAddress 속성입니다.
웹 응용 프로그램(ASP)의 경우.NET MVC 및 웹 양식 )
/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
var context = System.Web.HttpContext.Current;
string ip = String.Empty;
if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
ip = context.Request.UserHostAddress;
if (ip == "::1")
ip = "127.0.0.1";
return ip;
}
Windows 응용 프로그램(Windows Form, 콘솔, Windows Service , ...)
static void Main(string[] args)
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string a4 = a3[0];
Console.WriteLine(a4);
Console.ReadLine();
}
이 코드 스니펫들 중 많은 것들은 정말 크고 도움을 찾는 새로운 프로그래머들을 혼란스럽게 할 수 있습니다.
방문자의 IP 주소를 가져오는 간단하고 컴팩트한 이 코드는 어떻습니까?
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
단순하고 짧으며 콤팩트합니다.
확장 방법이 있습니다.
public static string GetIp(this HttpContextBase context)
{
if (context == null || context.Request == null)
return string.Empty;
return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
?? context.Request.UserHostAddress;
}
참고: "HTTP_X_FORWARED_FORWARDED_FOR"는 프록시 뒤에 있는 ip용입니다.맥락.부탁한다.UserHostAddress는 "REMOTE_ADDR"과 동일합니다.
하지만 실제 IP는 필요하지 않습니다.
출처:
내 버전은 ASP를 모두 처리합니다.NET 또는 LAN IP:
/**
* Get visitor's ip address.
*/
public static string GetVisitorIp() {
string ip = null;
if (HttpContext.Current != null) { // ASP.NET
ip = string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
? HttpContext.Current.Request.UserHostAddress
: HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
if (string.IsNullOrEmpty(ip) || ip.Trim() == "::1") { // still can't decide or is LAN
var lan = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(r => r.AddressFamily == AddressFamily.InterNetwork);
ip = lan == null ? string.Empty : lan.ToString();
}
return ip;
}
private string GetClientIpaddress()
{
string ipAddress = string.Empty;
ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipAddress == "" || ipAddress == null)
{
ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
return ipAddress;
}
else
{
return ipAddress;
}
}
MVC 5에서는 다음을 사용할 수 있습니다.
string cIpAddress = Request.UserHostAddress; //Gets the client ip address
또는
string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address
MVC에서 IP는 다음 코드로 얻을 수 있습니다.
string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
그냥 이것을 사용해요..............
public string GetIP()
{
string externalIP = "";
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
return externalIP;
}
우리는 외부 IP 주소를 제공하는 서버에 연결하고 반환되는 HTML 페이지에서 IP를 구문 분석하려고 합니다.그러나 서버가 이 페이지에서 작은 내용을 변경하거나 삭제하면 이러한 방법은 제대로 작동하지 않습니다.
여기 몇 년 동안 활성화된 서버를 사용하여 외부 IP 주소를 가져와서 간단한 응답을 빠르게 반환하는 방법이 있습니다...https://www.codeproject.com/Tips/452024/Getting-the-External-IP-Address
Private string getExternalIp()
{
try
{
string externalIP;
externalIP = (new
WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
catch { return null; }
}
VB.NET
Imports System.Net
Private Function GetExternalIp() As String
Try
Dim ExternalIP As String
ExternalIP = (New WebClient()).DownloadString("http://checkip.dyndns.org/")
ExternalIP = (New Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) _
.Matches(ExternalIP)(0).ToString()
Return ExternalIP
Catch
Return Nothing
End Try
함수 종료
lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();
xNet은 https://drive.google.com/open?id=1fmUosINo8hnDWY6s4IV4rDnHKLizX-Hq 에서 다운로드할 수 있습니다.
먼저 xNet, 코드를 가져와야 합니다.
using xNet;
코드:
void LoadpublicIP()
{
HttpRequest httprequest = new HttpRequest();
String HTML5 = httprequest.Get("https://whoer.net/").ToString();
MatchCollection collect = Regex.Matches(HTML5, @"<strong data-clipboard-target="".your-ip(.*?)</strong>", RegexOptions.Singleline);
foreach (Match match in collect)
{
var val = Regex.Matches(match.Value, @"(?<ip>(\d|\.)+)");
foreach (Match m in val)
{
richTextBox1.Text = m.Groups[2].Value;
}
}
}
언급URL : https://stackoverflow.com/questions/19285957/how-to-get-the-public-ip-address-of-a-user-in-c-sharp
'programing' 카테고리의 다른 글
항목이 없는 경우 오류 없이 존재하는지 확인 (0) | 2023.08.05 |
---|---|
데이터가 추가될 때 div 끝까지 자동 스크롤하는 방법은 무엇입니까? (0) | 2023.08.05 |
add(), replace() 및 addToBackStack()의 차이 (0) | 2023.08.05 |
Python Pandas:".value_counts" 출력을 데이터 프레임으로 변환 (0) | 2023.08.05 |
iframe의 현재 위치를 어떻게 알 수 있습니까? (0) | 2023.08.05 |