C# 始终在0-2秒内获取远程IP地址,具体取决于您的连接 public static WebClient webclient = new WebClient(); public static string GetIP() { string externalIP = ""; externalIP = 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地址显示为字符串并使用对象。以下是一些此类服务*:C# 始终在0-2秒内获取远程IP地址,具体取决于您的连接 public static WebClient webclient = new WebClient(); public static string GetIP() { string externalIP = ""; externalIP = 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; },c#,networking,ip-address,C#,Networking,Ip Address,通过@扩展此功能: 其中,您将使用一个服务,该服务仅将IP地址显示为字符串并使用对象。以下是一些此类服务*: *此问题中提到了一些服务,并且从中可以看出。解决方案中提到了大多数答案。对我们来说,结果不太好。我们已经面对了很多时间的流逝。如果你的程序依赖于IP检测,那真的很麻烦 作为解决方案,我们在其中一个桌面应用程序中使用以下方法: // Returns external/public ip protected string GetExternalIP()
*此问题中提到了一些服务,并且从中可以看出。解决方案中提到了大多数答案。对我们来说,结果不太好。我们已经面对了很多时间的流逝。如果你的程序依赖于IP检测,那真的很麻烦 作为解决方案,我们在其中一个桌面应用程序中使用以下方法:
// Returns external/public ip
protected string GetExternalIP()
{
try
{
using (MyWebClient client = new MyWebClient())
{
client.Headers["User-Agent"] =
"Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; " +
".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
try
{
byte[] arr = client.DownloadData("http://checkip.amazonaws.com/");
string response = System.Text.Encoding.UTF8.GetString(arr);
return response.Trim();
}
catch (WebException ex)
{
// Reproduce timeout: http://checkip.amazonaws.com:81/
// trying with another site
try
{
byte[] arr = client.DownloadData("http://icanhazip.com/");
string response = System.Text.Encoding.UTF8.GetString(arr);
return response.Trim();
}
catch (WebException exc)
{ return "Undefined"; }
}
}
}
catch (Exception ex)
{
// TODO: Log trace
return "Undefined";
}
}
好的方面是,两个站点都以普通格式返回IP。因此避免了字符串操作
要检查
catch
子句中的逻辑,可以通过点击不可用的端口来重现超时。例如:基本上我更喜欢使用一些额外的备份,以防其中一个IP无法访问。所以我用这个方法
public static string GetExternalIPAddress()
{
string result = string.Empty;
try
{
using (var client = new WebClient())
{
client.Headers["User-Agent"] =
"Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; " +
".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
try
{
byte[] arr = client.DownloadData("http://checkip.amazonaws.com/");
string response = System.Text.Encoding.UTF8.GetString(arr);
result = response.Trim();
}
catch (WebException)
{
}
}
}
catch
{
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://ipinfo.io/ip").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://api.ipify.org").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://icanhazip.com").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://wtfismyip.com/text").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("http://bot.whatismyipaddress.com/").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
string url = "http://checkip.dyndns.org";
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
System.Net.WebResponse resp = req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string response = sr.ReadToEnd().Trim();
string[] a = response.Split(':');
string a2 = a[1].Substring(1);
string[] a3 = a2.Split('<');
result = a3[0];
}
catch (Exception)
{
}
}
return result;
}
希望它有用
是包含此代码的应用程序示例 很好,因为它可以用原始文本和JSON进行响应。它还可以执行回调等操作。唯一的问题是它使用IPv4响应,而不是6。我发现它给了我必须处理的html标记,但只给了我一个简单的字符串。不幸的是给了我ip6地址,我需要ip4。幸运的是,您可以从ipv4.icanhazip.com和ipv6.icanhazip.com这两个子域中进行选择
string externalip = new WebClient().DownloadString("https://ipv4.icanhazip.com/");
Console.WriteLine(externalip);
Console.WriteLine(externalip.TrimEnd());
我已经将@Academy of Programmer的答案重构为较短的代码,并对其进行了修改,使其只命中
https://
URL:
public static string GetExternalIPAddress()
{
string result = string.Empty;
string[] checkIPUrl =
{
"https://ipinfo.io/ip",
"https://checkip.amazonaws.com/",
"https://api.ipify.org",
"https://icanhazip.com",
"https://wtfismyip.com/text"
};
using (var client = new WebClient())
{
client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
foreach (var url in checkIPUrl)
{
try
{
result = client.DownloadString(url);
}
catch
{
}
if (!string.IsNullOrEmpty(result))
break;
}
}
return result.Replace("\n", "").Trim();
}
}
基于使用外部web服务的答案并不完全正确,因为它们实际上没有回答所述问题: 。。。有关查找我的路由器的信息
解释 所有在线服务返回外部IP地址, 但这并不意味着该地址被分配给用户的路由器。 路由器可以被分配ISP基础设施网络的另一个本地IP地址。实际上,这意味着路由器不能承载互联网上的任何可用服务。这可能有利于大多数家庭用户的安全,但不利于在家中托管服务器的极客 下面是如何检查路由器是否有外部IP: 根据文章,IP地址范围
10.0.0.0–10.255.255
,172.16.0.0–172.31.255.255
和192.168.0.0–192.168.255.255
用于专用网络,即本地网络
查看在路由器被分配了外部IP地址的情况下,跟踪到某个远程主机的路由时发生的情况:
明白了!第一个跃点从31.*
开始。这显然意味着你的路由器和互联网之间没有任何联系
解决方案
Ttl=2对某个地址进行Ping操作
try
{
using (var ping = new Ping())
{
var pingResult = ping.Send("google.com");
if (pingResult?.Status == IPStatus.Success)
{
pingResult = ping.Send(pingResult.Address, 3000, "ping".ToAsciiBytes(), new PingOptions { Ttl = 2 });
var isRealIp = !Helpers.IsLocalIp(pingResult?.Address);
Console.WriteLine(pingResult?.Address == null
? $"Has {(isRealIp ? string.Empty : "no ")}real IP, status: {pingResult?.Status}"
: $"Has {(isRealIp ? string.Empty : "no ")}real IP, response from: {pingResult.Address}, status: {pingResult.Status}");
Console.WriteLine($"ISP assigned REAL EXTERNAL IP to your router, response from: {pingResult?.Address}, status: {pingResult?.Status}");
}
else
{
Console.WriteLine($"Your router appears to be behind ISP networks, response from: {pingResult?.Address}, status: {pingResult?.Status}");
}
}
}
catch (Exception exc)
{
Console.WriteLine("Failed to resolve external ip address by ping");
}
Small helper用于检查IP是否属于专用网络或公用网络:
public static bool IsLocalIp(IPAddress ip) {
var ipParts = ip.ToString().Split(new [] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
return (ipParts[0] == 192 && ipParts[1] == 168)
|| (ipParts[0] == 172 && ipParts[1] >= 16 && ipParts[1] <= 31)
|| ipParts[0] == 10;
}
公共静态bool IsLocalIp(ip地址ip){
var ipParts=ip.ToString().Split(新[]{“.”,StringSplitOptions.RemoveEmptyEntries)。选择(int.Parse.ToArray();
返回(ipParts[0]==192&&ipParts[1]==168)
||(ipParts[0]==172&&ipParts[1]>=16&&ipParts[1]我发现大多数其他答案都不存在,因为它们假设任何返回的字符串都必须是IP,但没有真正检查它。这是我目前使用的解决方案。
它只会返回有效的IP,如果找不到,则返回null
public class WhatsMyIp
{
public static IPAddress PublicIp { get; private set; }
static WhatsMyIp()
{
PublicIp = GetMyIp();
}
public static IPAddress GetMyIp()
{
List<string> services = new List<string>()
{
"https://ipv4.icanhazip.com",
"https://api.ipify.org",
"https://ipinfo.io/ip",
"https://checkip.amazonaws.com",
"https://wtfismyip.com/text",
"http://icanhazip.com"
};
using (var webclient = new WebClient())
foreach (var service in services)
{
try { return IPAddress.Parse(webclient.DownloadString(service)); } catch { }
}
return null;
}
}
公共类WhatsMyIp
{
公共静态IP地址PublicIp{get;private set;}
静态WhatsMyIp()
{
PublicIp=GetMyIp();
}
公共静态IP地址GetMyIp()
{
列表服务=新列表()
{
"https://ipv4.icanhazip.com",
"https://api.ipify.org",
"https://ipinfo.io/ip",
"https://checkip.amazonaws.com",
"https://wtfismyip.com/text",
"http://icanhazip.com"
};
使用(var webclient=new webclient())
foreach(服务中的var服务)
{
尝试{return IPAddress.Parse(webclient.DownloadString(service));}catch{}
}
返回null;
}
}
我和Jesper几乎一样,只是我重用了webclient并正确地处理了它。
此外,我还通过删除结尾处的多余\n来清理一些响应
专用静态IP地址GetExternalIp(){
使用(WebClient=newWebClient()){
列表主机=新列表();
主机。添加(“https://icanhazip.com");
主机。添加(“https://api.ipify.org");
主机。添加(“https://ipinfo.io/ip");
主机。添加(“https://wtfismyip.com/text");
主机。添加(“https://checkip.amazonaws.com/");
主机。添加(“https://bot.whatismyipaddress.com/");
主机。添加(“https://ipecho.net/plain");
foreach(主机中的字符串主机){
试一试{
String=client.DownloadString(主机);
ipAdressString=ipAdressString.Replace(“\n”,”);
返回IPAddress.Parse(IPAddressString);
}抓住{
}
}
}
返回null;
}
哪条路是“这条路”?您是否试图以编程方式执行此操作?使用CGN时,您的路由器可能没有公共地址。无需担心。我之所以这么说,是因为新成员通常不熟悉系统…谢谢。如果ISP使用CGN,这实际上无法获取路由器地址。它只会在第二个o上获取ISP路由器地址。404ne.回答得很好!顺便说一句,我不得不调用Trim()
查看http://ipinfo.io/ip
。有一个尾随空格。这将获得发球权
wget -qO- http://bot.whatismyipaddress.com
curl http://ipinfo.io/ip
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NATUPNPLib; // Add this dll from referance and chande Embed Interop Interop to false from properties panel on visual studio
using System.Net;
namespace Client
{
class NATTRAVERSAL
{
//This is code for get external ip
private void NAT_TRAVERSAL_ACT()
{
UPnPNATClass uPnP = new UPnPNATClass();
IStaticPortMappingCollection map = uPnP.StaticPortMappingCollection;
foreach (IStaticPortMapping item in map)
{
Debug.Print(item.ExternalIPAddress); //This line will give you external ip as string
break;
}
}
}
}
public IPAddress GetExternalIP()
{
WebClient lol = new WebClient();
string str = lol.DownloadString("http://www.ip-adress.com/");
string pattern = "<h2>My IP address is: (.+)</h2>"
MatchCollection matches1 = Regex.Matches(str, pattern);
string ip = matches1(0).ToString;
ip = ip.Remove(0, 21);
ip = ip.Replace("
", "");
ip = ip.Replace(" ", "");
return IPAddress.Parse(ip);
}
public static string PublicIPAddress()
{
string uri = "http://checkip.dyndns.org/";
string ip = String.Empty;
using (var client = new HttpClient())
{
var result = client.GetAsync(uri).Result.Content.ReadAsStringAsync().Result;
ip = result.Split(':')[1].Split('<')[0];
}
return ip;
}
public string GetClientIp() {
var ipAddress = string.Empty;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) {
ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
} else if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null &&
System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"].Length != 0) {
ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
} else if (System.Web.HttpContext.Current.Request.UserHostAddress.Length != 0) {
ipAddress = System.Web.HttpContext.Current.Request.UserHostName;
}
return ipAddress;
}
using System.Net;
private string GetWorldIP()
{
String url = "http://bot.whatismyipaddress.com/";
String result = null;
try
{
WebClient client = new WebClient();
result = client.DownloadString(url);
return result;
}
catch (Exception ex) { return "127.0.0.1"; }
}
string pubIp = new System.Net.WebClient().DownloadString("https://api.ipify.org");
connection list
RESP: 3947 17.110.226. 13:443 146.200.253. 16:60642 [R..A] Internet 6 tcp 128
<------------------ 39 -------------><-- WAN IP -->
private bool getWanIp(ref string wanIP)
{
string routerResponse = sendRouterCommand("connection list");
return (getWanIpFromRouterResponse(routerResponse, out wanIP));
}
private bool getWanIpFromRouterResponse(string routerResponse, out string ipResult)
{
ipResult = null;
string[] responseLines = routerResponse.Split(new char[] { '\n' });
// RESP: 3947 17.110.226. 13:443 146.200.253. 16:60642 [R..A] Internet 6 tcp 128
//<------------------ 39 -------------><--- 15 --->
const int offset = 39, length = 15;
foreach (string line in responseLines)
{
if (line.Length > (offset + length) && line.Contains("Internet"))
{
ipResult = line.Substring(39, 15).Replace(" ", "");
return true;
}
}
return false;
}
public static 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;
}
public static WebClient webclient = new WebClient();
public static string GetIP()
{
string externalIP = "";
externalIP = 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;
}
static System.Net.IPAddress GetPublicIp(string serviceUrl = "https://ipinfo.io/ip")
{
return System.Net.IPAddress.Parse(new System.Net.WebClient().DownloadString(serviceUrl));
}
private static string GetPublicIpAddress()
{
using (var client = new WebClient())
{
return client.DownloadString("http://ifconfig.me").Replace("\n", "");
}
}
// Returns external/public ip
protected string GetExternalIP()
{
try
{
using (MyWebClient client = new MyWebClient())
{
client.Headers["User-Agent"] =
"Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; " +
".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
try
{
byte[] arr = client.DownloadData("http://checkip.amazonaws.com/");
string response = System.Text.Encoding.UTF8.GetString(arr);
return response.Trim();
}
catch (WebException ex)
{
// Reproduce timeout: http://checkip.amazonaws.com:81/
// trying with another site
try
{
byte[] arr = client.DownloadData("http://icanhazip.com/");
string response = System.Text.Encoding.UTF8.GetString(arr);
return response.Trim();
}
catch (WebException exc)
{ return "Undefined"; }
}
}
}
catch (Exception ex)
{
// TODO: Log trace
return "Undefined";
}
}
public static string GetExternalIPAddress()
{
string result = string.Empty;
try
{
using (var client = new WebClient())
{
client.Headers["User-Agent"] =
"Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; " +
".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
try
{
byte[] arr = client.DownloadData("http://checkip.amazonaws.com/");
string response = System.Text.Encoding.UTF8.GetString(arr);
result = response.Trim();
}
catch (WebException)
{
}
}
}
catch
{
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://ipinfo.io/ip").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://api.ipify.org").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://icanhazip.com").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://wtfismyip.com/text").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("http://bot.whatismyipaddress.com/").Replace("\n", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
string url = "http://checkip.dyndns.org";
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
System.Net.WebResponse resp = req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string response = sr.ReadToEnd().Trim();
string[] a = response.Split(':');
string a2 = a[1].Substring(1);
string[] a3 = a2.Split('<');
result = a3[0];
}
catch (Exception)
{
}
}
return result;
}
void GetPublicIPAddress()
{
Task.Factory.StartNew(() =>
{
var ipAddress = SystemHelper.GetExternalIPAddress();
Action bindData = () =>
{
if (!string.IsNullOrEmpty(ipAddress))
labelMainContent.Content = "IP External: " + ipAddress;
else
labelMainContent.Content = "IP External: ";
labelMainContent.Visibility = Visibility.Visible;
};
this.Dispatcher.InvokeAsync(bindData);
});
}
string externalip = new WebClient().DownloadString("https://ipv4.icanhazip.com/");
Console.WriteLine(externalip);
Console.WriteLine(externalip.TrimEnd());
public static string GetExternalIPAddress()
{
string result = string.Empty;
string[] checkIPUrl =
{
"https://ipinfo.io/ip",
"https://checkip.amazonaws.com/",
"https://api.ipify.org",
"https://icanhazip.com",
"https://wtfismyip.com/text"
};
using (var client = new WebClient())
{
client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
"(compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
foreach (var url in checkIPUrl)
{
try
{
result = client.DownloadString(url);
}
catch
{
}
if (!string.IsNullOrEmpty(result))
break;
}
}
return result.Replace("\n", "").Trim();
}
}
try
{
using (var ping = new Ping())
{
var pingResult = ping.Send("google.com");
if (pingResult?.Status == IPStatus.Success)
{
pingResult = ping.Send(pingResult.Address, 3000, "ping".ToAsciiBytes(), new PingOptions { Ttl = 2 });
var isRealIp = !Helpers.IsLocalIp(pingResult?.Address);
Console.WriteLine(pingResult?.Address == null
? $"Has {(isRealIp ? string.Empty : "no ")}real IP, status: {pingResult?.Status}"
: $"Has {(isRealIp ? string.Empty : "no ")}real IP, response from: {pingResult.Address}, status: {pingResult.Status}");
Console.WriteLine($"ISP assigned REAL EXTERNAL IP to your router, response from: {pingResult?.Address}, status: {pingResult?.Status}");
}
else
{
Console.WriteLine($"Your router appears to be behind ISP networks, response from: {pingResult?.Address}, status: {pingResult?.Status}");
}
}
}
catch (Exception exc)
{
Console.WriteLine("Failed to resolve external ip address by ping");
}
public static bool IsLocalIp(IPAddress ip) {
var ipParts = ip.ToString().Split(new [] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
return (ipParts[0] == 192 && ipParts[1] == 168)
|| (ipParts[0] == 172 && ipParts[1] >= 16 && ipParts[1] <= 31)
|| ipParts[0] == 10;
}
public class WhatsMyIp
{
public static IPAddress PublicIp { get; private set; }
static WhatsMyIp()
{
PublicIp = GetMyIp();
}
public static IPAddress GetMyIp()
{
List<string> services = new List<string>()
{
"https://ipv4.icanhazip.com",
"https://api.ipify.org",
"https://ipinfo.io/ip",
"https://checkip.amazonaws.com",
"https://wtfismyip.com/text",
"http://icanhazip.com"
};
using (var webclient = new WebClient())
foreach (var service in services)
{
try { return IPAddress.Parse(webclient.DownloadString(service)); } catch { }
}
return null;
}
}