我看看不到或找不到有关发现我的路由人公开IP的信息? 这样做是因为它必须如此做,而且必须从一个网站上获取?
What is the use of default keyword in C#? Is it introduced in C# 3.0 ?
我看看不到或找不到有关发现我的路由人公开IP的信息? 这样做是因为它必须如此做,而且必须从一个网站上获取?
<>Using C#, with HTTPClient
using async methods
public static async Task<IPAddress?> GetExternalIpAddress()
{
var externalIpString = (await new HttpClient().GetStringAsync("http://icanhazip.com"))
.Replace("\r\n", "").Replace("\n", "").Trim();
if(!IPAddress.TryParse(externalIpString, out var ipAddress)) return null;
return ipAddress;
}
public static void Main(string[] args)
{
var externalIpTask = GetExternalIpAddress();
GetExternalIpAddress().Wait();
var externalIpString = externalIpTask.Result ?? IPAddress.Loopback;
Console.WriteLine(externalIpString);
}
<>Obsolete C#, with WebClient
.
public static void Main(string[] args)
{
string externalIpString = new WebClient().DownloadString("http://icanhazip.com").Replace("\r\n", "").Replace("\n", "").Trim();
var externalIp = IPAddress.Parse(externalIpString);
Console.WriteLine(externalIp.ToString());
}
<>Command Line(关于Windows和Windows的工程)
wget -qO- http://bot.whatismyipaddress.com
<<>Curl
curl http://ipinfo.io/ip
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();
}
http://checkip.dyndns.org“rel=“noreferer” IP DNS
http://www.goldb.org/getcsharp.html Goldb-Httpget C#
string pubIp = new System.Net.WebClient().DownloadString("https://api.ipify.org");
网上查询:
public static string GetPublicIP()
{
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( < );
string a4 = a3[0];
return a4;
}
利用类似的服务
private string GetPublicIpAddress()
{
var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");
request.UserAgent = "curl"; // this will tell the server to return the information as if the request was made by the linux "curl" command
string publicIPAddress;
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
publicIPAddress = reader.ReadToEnd();
}
}
return publicIPAddress.Replace("
", "");
}
https://stackoverflow.com/questions/3253701/get-public-external-ip-address#answer-30911062” a)
static System.Net.IPAddress GetPublicIp(string serviceUrl = "https://ipinfo.io/ip")
{
return System.Net.IPAddress.Parse(new System.Net.WebClient().DownloadString(serviceUrl));
}
如果你使用System.Net.WebClient
这简单地显示IP地址为示意图和用途:https://msdn.microsoft.com/en-us/library/system.net.ipaddress.aspx”rel=“noreferer”>System.Net.IPAddress/code>
反对。 这里有几个这样的服务*:
* E/CN.6/2009/1。 这里提到了一些服务,从,从超级用户网站获得的水塔。
从理论上讲,你的路由人应当能够告诉你网络的公共IP地址,但这样做的方法必然会不一致,甚至可能有些路由装置。
最容易而且仍然非常可靠的方法是向网页发送请求书,在网站服务器看到时将你的IP地址退回。 登格斯.org为此提供了良好的服务:
返还的是一种极为简单的/短的超文本文件,其中载有以下案文:Current IP Address:157.221.82.39
(fake IP),这是从吉大港山区海岸警卫队反应中提取的三维。
I found that http://checkip.dyndns.org/ 下面请我:html的标签,我必须处理,但https://icanhazip.com/。 只是给我一个简单的例子。 遗憾的是,https://icanhazip.com/。 给我6月的讲话,我需要4。 很幸运的是,你可以从Pipv4.icanhazip.com和Pipv6.icanhazip.com选择了2个子。
string externalip = new WebClient().DownloadString("https://ipv4.icanhazip.com/");
Console.WriteLine(externalip);
Console.WriteLine(externalip.TrimEnd());
有了几条密码,你可以为此写上自己的Http服务器。
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://+/PublicIP/");
listener.Start();
while (true)
{
HttpListenerContext context = listener.GetContext();
string clientIP = context.Request.RemoteEndPoint.Address.ToString();
using (Stream response = context.Response.OutputStream)
using (StreamWriter writer = new StreamWriter(response))
writer.Write(clientIP);
context.Response.Close();
}
然后,你需要知道你的公众,你可以这样做。
WebClient client = new WebClient();
string ip = client.DownloadString("http://serverIp/PublicIP");
在基本情况下,如果一个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("
", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://api.ipify.org").Replace("
", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://icanhazip.com").Replace("
", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("https://wtfismyip.com/text").Replace("
", "");
}
catch
{
}
}
if (string.IsNullOrEmpty(result))
{
try
{
result = new WebClient().DownloadString("http://bot.whatismyipaddress.com/").Replace("
", "");
}
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;
}
为了更新全球倡议控制(WPF,NET 4.5),例如一些Label I使用该守则
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);
});
}
希望是有益的。
I find most of the other answers lacking as they assume that any returned string must be the IP, but doesn t really check for it. This is my solution that I m currently using. It will only return a valid IP or null if none is found.
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;
}
}
检查结果。 例如,对于我的机器来说,它显示的是内部的NAT地址:
Current IP Address: 192.168.1.120
I think its happening, because of I have my local DNS-zone behind NAT, and my browser sends to checkip its local IP address, which is returned back.
Also, http is heavy weight and text oriented TCP-based protocol, so not very suitable for quick and efficient regular request for external IP address. I suggest to use UDP-based, binary STUN, especially designed for this purposes:
http://en.wikipedia.org/wiki/STUN
STUN-server与“UDP”一样。 阁下,见“我看一看”。
There is many public STUN-servers over the world, where you can request your external IP. For example, see here:
http://www.voip-info.org/wiki/view/STUN
您可从互联网上下载任何联合国图书馆,例如:
http://www.codeproject.com/Articles/18492/STUN-Client 。
并且使用。
快速进入外部管道,没有任何联系 实际不需要任何Http链接
first you must add NATUPNPLib.dll on Referance And select it from referances and check from properties window Embed Interop Type to False
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;
}
}
}
}
以外部网络服务为基础的答复并不准确,因为它们实际上没有回答所述问题:
......关于发现<斯特隆>米路由器的公开IP
解释
All online services return the external IP address, but it does not essentially mean, that this address is assigned to the user s router.
路线者可被分配到ISP基础设施网络的另一个当地IP地址。 实际上,这意味着该路由人不能接收任何互联网上的服务。 这对于大多数家庭用户的安全来说可能很好,但对于在家中接收服务器的格凯克人来说并不好。
这里如何检查路由人是否拥有外部IP:
参看你向一些边远的东道国指明路线,由外部IP地址分配路由:
Gotcha! 首先从31.*
开始。 这显然意味着,你的路由和互联网之间没有任何东西。
解决办法
Ttl = 2
TTL=2必须不足以到达遥远的东道国。 Hop #1的东道方将采用“Reply from <ip Address> TTL过期于中途<>/code>,显示其IP地址。
执行
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;
}
private static string GetPublicIpAddress()
{
using (var client = new WebClient())
{
return client.DownloadString("http://ifconfig.me").Replace("
", "");
}
}
当我 de笑时,我利用下面建造外部可打电话的URL,但你只能使用头两条线,使你的公共IP:
public static string ExternalAction(this UrlHelper helper, string actionName, string controllerName = null, RouteValueDictionary routeValues = null, string protocol = null)
{
#if DEBUG
var client = new HttpClient();
var ipAddress = client.GetStringAsync("http://ipecho.net/plain").Result;
// above 2 lines should do it..
var route = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues, helper.RouteCollection, helper.RequestContext, true);
if (route == null)
{
return route;
}
if (string.IsNullOrEmpty(protocol) && string.IsNullOrEmpty(ipAddress))
{
return route;
}
var url = HttpContext.Current.Request.Url;
protocol = !string.IsNullOrWhiteSpace(protocol) ? protocol : Uri.UriSchemeHttp;
return string.Concat(protocol, Uri.SchemeDelimiter, ipAddress, route);
#else
helper.Action(action, null, null, HttpContext.Current.Request.Url.Scheme)
#endif
}
页: 1
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;
}
www.un.org/Depts/DGACM/index_spanish.htm 最佳答案一见。
尽快解决边远问题。 你们必须使用下载器,或在你的电脑上建立服务器。
采用这一简单法典的倒数部分(建议)是,需要3至5秒才能获得你的远程IP地址,因为网上广播在开始时总是需要3至5秒才能检查你的代理环境。
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;
}
这里是我是如何确定的(第一次需要3至5秒),但此后,根据您的联系,我总是在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;
}
缩略语 URLs:
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("
", "").Trim();
}
}
您可使用Telnet,在方案上查询广域网的路由器。
www.un.org/Depts/DGACM/index_spanish.htm Telnet part
Telnet部分可通过以下方式实现:,作为向路主发送电话线,并接受路由人的回应的APIC。 其余的答复假定,你以某种方式设立,以派遣一个Telnet指挥所,并在你的法典中收回答复。
<>方法范围>
我将首先指出,与其它做法相比,对路由人进行询问的一个缺点是,你写的法典可能与你的航道模式相当具体。 尽管如此,这可以成为一种有用的办法,不依赖外部服务器,而且你可能愿意为其他目的从您自己的软件中获取你的路由,例如配置和控制软件,从而使其更值得撰写具体的代码。
www.un.org/Depts/DGACM/index_spanish.htm 例路由指挥和控制
下面的例子并非所有航道者都正确,而是在原则上说明做法。 你们需要改变细节,以适应你的航道指挥和反应。
例如,获得你的路由显示广域网的路由器,可能是以下Telnet指挥:
connection list
产出可能包括一个文本线清单,每个链接一个,IP地址为39。 广域网连接线可从“因特网”这一行文中某些地方识别:
RESP: 3947 17.110.226. 13:443 146.200.253. 16:60642 [R..A] Internet 6 tcp 128
<------------------ 39 -------------><-- WAN IP -->
产出可把每个IP地址部分分成三个具有空间的特性,需要删除。 (在上文xample,你需要将“146.200.253.16”改为“146.200.253.16”。)
通过为您的路由人试验或咨询参考文件,你可以确定指挥,供您的具体路由人使用,以及如何解释航道者的反应。
www.un.org/Depts/DGACM/index_spanish.htm 获取广域网
sendRouterCommand
for the Telnet part - 见上文。
采用上述实例路由器,以下代码向广域网提供:
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[] {
});
// 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;
}
大部分答复都提到“http://checkip.dyndns.org” rel=“nofollow”http://checkip.dyndns.org。 对我们来说,它做得很好。 我们面临很多时间。 如果你的方案取决于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。 避免了大规模行动。
https://api.ipification.org” rel=“nofollow> IPIFY AP是冰,因为它可以在原始文本和JSON中做出反应。 它还可以进行呼吁等。 唯一的问题是在IPv4,而不是6中。
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"; }
}
使用回落作为后退,以致事情不会致命地中断。
I had almost the same as Jesper, only I reused the webclient and disposed it correctly. Also I cleaned up some responses by removing the extra at the end.
private static IPAddress GetExternalIp () {
using (WebClient client = new WebClient()) {
List<String> hosts = new List<String>();
hosts.Add("https://icanhazip.com");
hosts.Add("https://api.ipify.org");
hosts.Add("https://ipinfo.io/ip");
hosts.Add("https://wtfismyip.com/text");
hosts.Add("https://checkip.amazonaws.com/");
hosts.Add("https://bot.whatismyipaddress.com/");
hosts.Add("https://ipecho.net/plain");
foreach (String host in hosts) {
try {
String ipAdressString = client.DownloadString(host);
ipAdressString = ipAdressString.Replace("
", "");
return IPAddress.Parse(ipAdressString);
} catch {
}
}
}
return null;
}
WebClient, WebRequest and many other are obsolete, consider using it:
public static IPAddress? GetExternalIP ()
{
try
{
using (var client = new HttpClient())
return IPAddress.Parse(client.GetAsync("http://ipinfo.io/ip").Result.Content.ReadAsStringAsync().Result);
}
catch (Exception ex)
{
return null;
}
}
晚年
private static string GetLocalAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork))
{
if (!string.IsNullOrEmpty(ip.ToString())) return ip.ToString();
}
return string.Empty;
}
What is the use of default keyword in C#? Is it introduced in C# 3.0 ?
I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...
I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...
I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...
I have two EF entities. One has a property called HouseNumber. The other has two properties, one called StartHouseNumber and one called EndHouseNumber. I want to create a many to many association ...
How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...
Since I cannot order my dictionary, what is the best way of going about taking key value pairs and also maintaing an index?
Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...