Это зависит от того, о каком диапазоне вы говорите, но динамический диапазон увеличивается до 65535 или 2 ^ 16-1 (16 бит).
http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
using System.Net;
string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());
Только что протестировал это на моей машине, и он работает.
namespace NKUtilities
{
using System;
using System.Net;
using System.Net.Sockets;
public class DNSUtility
{
public static int Main(string [] args)
{
string strHostName = "";
try {
if(args.Length == 0)
{
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine ("Local Machine's Host Name: " + strHostName);
}
else
{
// Otherwise, get the IP address of the host provided on the command line.
strHostName = args[0];
}
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for(int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
return 0;
}
catch(SocketException se)
{
Console.WriteLine("{0} ({1})", se.Message, strHostName);
return -1;
}
catch(Exception ex)
{
Console.WriteLine("Error: {0}.", ex.Message);
return -1;
}
}
}
}
Подробности смотрите здесь
Вы должны помнить, что ваш компьютер может иметь более одного IP-адреса (на самом деле он всегда так и есть) - так какой из них вам нужен.
Нет, это лучший способ сделать это. Поскольку машина может иметь несколько IP-адресов, вам необходимо перебрать их коллекцию, чтобы найти правильный.
Изменить: Единственное, что я изменил бы, это чтобы изменить это:
if (ip.AddressFamily.ToString() == "InterNetwork")
на это:
if (ip.AddressFamily == AddressFamily.InterNetwork)
Нет необходимости в ToString
перечисление для сравнения.
Возможно, с помощью внешнего IP-адреса вы можете рассмотреть (если вы находитесь в контексте веб-сервера), используя этот
Request.ServerVariables["LOCAL_ADDR"];
, я задавал тот же вопрос, что и вы, и я его нашел в этой статье stackoverflow.
У меня это сработало.
Единственный способ узнать ваш общедоступный IP-адрес - это попросить кого-нибудь рассказать вам; этот код может вам помочь:
public string GetPublicIP()
{
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
return direction;
}