I'm trying to parse a string containing an IP address and a port using IPAddress.Parse. This works well with IPv6 addresses but not with IPv4 addresses. Can somone explain why this happens?
The code I'm using is:
IPAddress.Parse("[::1]:5"); //Valid
IPAddress.Parse("127.0.0.1:5"); //null
Uri url;
IPAddress ip;
if (Uri.TryCreate(String.Format("http://{0}", "127.0.0.1:5"), UriKind.Absolute, out url) &&
IPAddress.TryParse(url.Host, out ip))
{
IPEndPoint endPoint = new IPEndPoint(ip, url.Port);
}
This happens because the port is not part of the IP address. It belongs to TCP/UDP, and you'll have to strip it out first. The Uri class might be helpful for this.
IPAddress is not IP+Port. You want IPEndPoint.
Example from http://www.java2s.com/Code/CSharp/Network/ParseHostString.htm
public static void ParseHostString(string hostString, ref string hostName, ref int port)
{
hostName = hostString;
if (hostString.Contains(":"))
{
string[] hostParts = hostString.Split(':');
if (hostParts.Length == 2)
{
hostName = hostParts[0];
int.TryParse(hostParts[1], out port);
}
}
}
Edit: Ok, I'll admit that wasn't the most elegant solution. Try this one I wrote (just for you) instead:
// You need to include some usings:
using System.Text.RegularExpressions;
using System.Net;
// Then this code (static is not required):
private static Regex hostPortMatch = new Regex(#"^(?<ip>(?:\[[\da-fA-F:]+\])|(?:\d{1,3}\.){3}\d{1,3})(?::(?<port>\d+))?$", System.Text.RegularExpressions.RegexOptions.Compiled);
public static IPEndPoint ParseHostPort(string hostPort)
{
Match match = hostPortMatch.Match(hostPort);
if (!match.Success)
return null;
return new IPEndPoint(IPAddress.Parse(match.Groups["ip"].Value), int.Parse(match.Groups["port"].Value));
}
Note that this one ONLY accepts IP address, not hostname. If you want to support hostname you'll either have to resolve it to IP or not use IPAddress/IPEndPoint.
IPAddress.Parse is meant to take A string that contains an IP address in dotted-quad notation for IPv4 and in colon-hexadecimal notation for IPv6. So your first example works for IPv6 and your second example fails because it doesnt support a port for IPv4. Link http://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx
As Tedd Hansen pointed out, what you are trying to parse is not an IP address but an IP endpoint (IP address + port). And since .NET Core 3.0, you can use IPEndPoint.TryParse to parse a string as an IPEndPoint:
if (IPEndPoint.TryParse("127.0.0.1:5", out IPEndPoint endpoint))
{
// parsed successfully, you can use the "endpoint" variable
Console.WriteLine(endpoint.Address.ToString()); // writes "127.0.0.1"
Console.WriteLine(endpoint.Port.ToString()); // writes "5"
}
else
{
// failed to parse
}
If you work on older versions of .net you can take IPEndPoint.Parse implementation from open source: https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs
To add my two cents... Since Microsoft itself implemented TryParse in NET Core 3.0 I've opted to stop using my custom IP+Port parser and kindly borrowed their code with some adaptations:
public static class IPEndPointParserExtension
{
public static bool TryParseAsIPEndPoint(this string s, out IPEndPoint result) {
#if NETCOREAPP3_0_OR_GREATER
return IPEndPoint.TryParse(s, out result);
#else
int addressLength = s.Length; // If there's no port then send the entire string to the address parser
int lastColonPos = s.LastIndexOf(':');
// Look to see if this is an IPv6 address with a port.
if (lastColonPos > 0) {
if (s[lastColonPos - 1] == ']')
addressLength = lastColonPos;
// Look to see if this is IPv4 with a port (IPv6 will have another colon)
else if (s.Substring(0, lastColonPos).LastIndexOf(':') == -1)
addressLength = lastColonPos;
}
if (IPAddress.TryParse(s.Substring(0, addressLength), out IPAddress address)) {
long port = 0;
if (addressLength == s.Length ||
(long.TryParse(s.Substring(addressLength + 1), out port)
&& port <= IPEndPoint.MaxPort)) {
result = new IPEndPoint(address, (int)port);
return true;
}
}
result = null;
return false;
#endif
}
public static IPEndPoint AsIPEndPoint(this string s) =>
s.TryParseAsIPEndPoint(out var endpoint)
? endpoint
: throw new FormatException($"'{s}' is not a valid IP Endpoint");
}
My changes were to basically exchange Span<char> for string and make it an extension method of the class String itself. I've also conditionally compile to use Microsoft's implementation if it is available (NET Core 3.0 or greater).
The following nUnit tests show how to use the code:
[Test]
public void CanParseIpv4WithPort() {
var sIp = "192.168.0.233:8080";
if (sIp.TryParseAsIPEndPoint(out var endpoint)) {
var expected = new IPEndPoint(new IPAddress(new byte[] { 192, 168, 0, 233 }), 8080);
Assert.AreEqual(expected, endpoint);
} else
Assert.Fail($"Failed to parse {sIp}");
}
[Test]
public void CanParseIpv6WithPort() {
var sIp = "[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443";
if (sIp.TryParseAsIPEndPoint(out var endpoint)) {
var expected = new IPEndPoint(IPAddress.Parse("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 443);
Assert.AreEqual(expected, endpoint);
} else
Assert.Fail($"Failed to parse {sIp}");
}
You can also use AsIpEndPoint which will throw an exception if it fails to parse the IP address and port (port is optional):
var ep = "127.0.0.1:9000".AsIPEndPoint();
Related
I wish to hide my IP when connecting to IRC via my .NET app. I currently use the IrcDotNet library but it doesn't seems to support proxies.
I've not had much experience with sockets, so I think modifying IrcDotNet would be easier than making my own IRC library. I looked around for socket libraries that handle proxy connections that I could implement in IrcDotNet. I found one called ProxySocket but it only supports BeginConnect not the new ASyncConnect method that IrcDotNet uses.
To break it down, in order of preference, here's what I'm looking for;
An IRC library that supports connecting via a HTTP/SOCKS proxy
A socket library that supports connecting via a HTTP/SOCKS proxy via
ASyncConnect
Example code on how to extend the socket class to support connecting
via a HTTP/SOCKS proxy via ASyncConnect
The version of IrcDotNet I am using is 0.4.1 found at https://launchpad.net/ircdotnet.
Update 1: Still no luck i'm afraid. Fredrik92's answer, while helpful, is not applicable to the version of IrcDotNet I am using (see above).
The IRC.NET library uses the standard Socket class in the System.Net.Sockets namespace.
So you could just modify the IrcDotNet/IrcClient.cs file in the IRC.NET source code (# http://ircdotnet.codeplex.com/SourceControl/latest).
You should add a constructor for proxy enabled IRC clients and call the default constructor.
Then all you should need to do is to modify the Connect methods in the same file (almost at the bottom). Each time they call this.client.BeginConnect(..) you have to add code for connecting to the Proxy (instead of the remote host)
Now you only have to create a new Connect-callback method that sends a HTTP CONNECT request to the proxy. Read the response from the HTTP Proxy and then everything else should work.
In this case I would write the HTTP request as raw ASCII bytes to the Proxy (instead of using the HttpWebRequest class), so that you have full control over the network stream you get in return...
You should add sth. like this to the IrcClient class:
private bool useProxy = false;
private IWebProxy proxy;
private IEnumerable<Uri> proxyRemoteUris;
public IrcClient(IWebProxy proxy)
: this()
{
this.useProxy = true;
this.proxy = proxy;
}
private void ProxyPerformHttpConnect(Uri remoteIrcUri)
{
string httpConnectRequest = string.Format("CONNECT {0}:{1} HTTP/1.1\r\nHost: {2}\r\n\r\n",
remoteIrcUri.Host, remoteIrcUri.Port, this.proxy.GetProxy(remoteIrcUri));
byte[] httpConnectData = Encoding.ASCII.GetBytes(httpConnectRequest);
this.stream.Write(httpConnectData, 0, httpConnectData.Length);
bool responseReady = false;
string responseText = string.Empty;
// Byte-by-byte reading required, because StringReader will read more than just the HTTP response header
do
{
int readByte = this.stream.ReadByte();
if (readByte < 0)
throw new WebException(message: null, status: WebExceptionStatus.ConnectionClosed);
char readChar = (char)(readByte); // Only works because HTTP Headers are ASCII encoded.
responseText += readChar;
responseReady = responseText.EndsWith("\r\n\r\n");
} while (!responseReady);
int statusStart = responseText.IndexOf(' ') + 1;
int reasonStart = responseText.IndexOf(' ', statusStart) + 1;
int reasonEnd = responseText.IndexOfAny(new char[] { '\r', '\n'});
HttpStatusCode responseStatus = (HttpStatusCode)(int.Parse(responseText.Substring(responseText.IndexOf(' ') + 1, length: 3)));
if (responseStatus != HttpStatusCode.OK)
{
string reasonText = responseText.Substring(reasonStart, reasonEnd - reasonStart);
if (string.IsNullOrWhiteSpace(reasonText))
reasonText = null;
throw new WebException(reasonText, WebExceptionStatus.ConnectFailure);
}
// Finished Response Header read...
}
private void ProxyConnectCallback(IAsyncResult ar)
{
try
{
this.client.EndConnect(ar);
this.stream = this.client.GetStream();
bool proxyTunnelEstablished = false;
WebException lastWebException = null;
foreach (Uri remoteIrcUri in this.proxyRemoteUris)
{
if (this.client.Connected == false)
{
// Re-establish connection with proxy...
Uri proxyUri = this.proxy.GetProxy(remoteIrcUri);
this.client.Connect(proxyUri.Host, proxyUri.Port);
}
try
{
ProxyPerformHttpConnect(remoteIrcUri);
proxyTunnelEstablished = true;
break;
}
catch (WebException webExcept)
{
lastWebException = webExcept;
}
}
if (!proxyTunnelEstablished)
{
OnConnectFailed(new IrcErrorEventArgs(lastWebException));
return;
}
this.writer = new StreamWriter(this.stream, Encoding.Default);
this.reader = new StreamReader(this.stream, Encoding.Default);
HandleClientConnected((IrcRegistrationInfo)ar.AsyncState);
this.readThread.Start();
this.writeThread.Start();
OnConnected(new EventArgs());
}
catch (Exception ex)
{
OnConnectFailed(new IrcErrorEventArgs(ex));
}
}
The code for the proxy handling in all Connect methods of the IrcClient class would thus look sth. like this:
// Code snippet to insert before the call to this.client.BeginConnect(...)
if (this.useProxy)
{
// Assign host and port variables for EndPoint objects:
// var host = remoteEP.Address;
// var port = remoteEP.Port;
this.proxyRemoteUris = new Uri[] { new Uri(string.Format("irc://{0}:{1}/", host, port)) };
// Replace the line above with the following line in the method where an array of IP addresses is specified as a parameter
// this.proxyRemoteUris = from ip in addresses select new Uri(string.Format("irc://{0}:{1}/", ip, port));
Uri proxyUri = this.proxy.GetProxy(this.proxyRemoteUris.First());
string proxyHost = proxyUri.Host;
int proxyPort = proxyUri.Port;
this.client.BeginConnect(proxyHost, proxyPort, ProxyConnectCallback, registrationInfo);
}
else
// Original this.client.BeginConnect(...) call here...
I'm using Xamarin + MonoTouch on iOS to browse for a web server on the network that I can then download files from.
The NSNetService that is passed into the resolve event handler contains addresses as NSData. I can't find a good way to turn that NSData into an actual IP address that I can then build a URL from, i.e. http:// < IPAddress > /folder/file.htm
This is my NSNetService.AddressResolved event handler:
private void OnServiceResolved(object sender, EventArgs args)
{
NSNetService service = (NSNetService)sender;
// service.Port is valid.
// service.HostName is valid.
// but we want the IP addres, which is in service.Addresses.
// None of the following four methods works quite right.
IPAddress address = (IPAddress)service.Addresses [0]; // Cannot convert type NSData to IPAddress
SocketAddress address2 = (SocketAddress)service.Addresses[0]; // Cannot convert NSData to SocketAddress. A binary copy might work?
IPHostEntry entry = (IPHostEntry)service.Addresses [0]; // Cannot convert NSData to IPHostEntry
IPHostEntry entry2 = Dns.GetHostByName (service.HostName); // This kinda works, but is dumb. Didn't we just resolve?
}
What's the right way to get the IP address of the service from an NSNetService in a resolve event?
The NSNetService.Addresses property gives you NSData instances which must be converted into something that IPAddress (or other .NET types) can digest. E.g.
MemoryStream ms = new MemoryStream ();
(ns.Addresses [0] as NSData).AsStream ().CopyTo (ms);
IPAddress ip = new IPAddress (ms.ToArray ());
Note that this can return you an IPv6 address (or format that IPAddress won't accept). You might want to iterate all the Addresses to find the best one.
I'll look into adding a convenience method into future versions of Xamarin.iOS.
UPDATE
A more complete version, that returns an IPAddress, would look like:
static IPAddress CreateFrom (NSData data)
{
byte[] address = null;
using (MemoryStream ms = new MemoryStream ()) {
data.AsStream ().CopyTo (ms);
address = ms.ToArray ();
}
SocketAddress sa = new SocketAddress (AddressFamily.InterNetwork, address.Length);
// do not overwrite the AddressFamily we provided
for (int i = 2; i < address.Length; i++)
sa [i] = address [i];
IPEndPoint ep = new IPEndPoint (IPAddress.Any, 0);
return (ep.Create (sa) as IPEndPoint).Address;
}
I am currently working on a C# project where I need to validate the text that a user has entered into a text box.
One of the validations required is that it checks to ensure that an IP address has been entered correctly.
How would I go about doing this validation of the IP address.
Thanks for any help you can provide.
You can use IPAddress.Parse Method .NET Framework 1.1. Or, if you are using .NET 4.0, see documentation for IPAddress.TryParse Method .NET Framework 4.
This method determines if the contents of a string represent a valid IP address. In .NET 1.1, the return value is the IP address. In .NET 4.0, the return value indicates success/failure, and the IP address is returned in the IPAddress passed as an out parameter in the method call.
edit: alright I'll play the game for bounty :) Here's a sample implementation as an extension method, requiring C# 3+ and .NET 4.0:
using System;
using System.Net;
using System.Text.RegularExpressions;
namespace IPValidator
{
class Program
{
static void Main (string[] args)
{
Action<string> TestIP = (ip) => Console.Out.WriteLine (ip + " is valid? " + ip.IsValidIP ());
TestIP ("99");
TestIP ("99.99.99.99");
TestIP ("255.255.255.256");
TestIP ("abc");
TestIP ("192.168.1.1");
}
}
internal static class IpExtensions
{
public static bool IsValidIP (this string address)
{
if (!Regex.IsMatch (address, #"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"))
return false;
IPAddress dummy;
return IPAddress.TryParse (address, out dummy);
}
}
}
It seems that you are only concerned with validating IPv4 IP Address strings in X.X.X.X format. If so, this code is straight forward for that task:
string ip = "127.0.0.1";
string[] parts = ip.Split('.');
if (parts.Length < 4)
{
// not a IPv4 string in X.X.X.X format
}
else
{
foreach(string part in parts)
{
byte checkPart = 0;
if (!byte.TryParse(part, out checkPart))
{
// not a valid IPv4 string in X.X.X.X format
}
}
// it is a valid IPv4 string in X.X.X.X format
}
If you want to see if the IP address actually exists, you can use the Ping class.
insta's answer was closer before he added the incorrect regexp.
public static bool IsValidIP(string ipAddress)
{
IPAddress unused;
return IPAddress.TryParse(ipAddress, out unused);
}
Or since the OP doesn't want to include integer IPv4 addresses that aren't full dotted quads:
public static bool IsValidIP(string ipAddress)
{
IPAddress unused;
return IPAddress.TryParse(ipAddress, out unused)
&&
(
unused.AddressFamily != AddressFamily.InterNetwork
||
ipAddress.Count(c => c == '.') == 3
);
}
Testing:
IsValidIP("fe80::202:b3ff:fe1e:8329") returns true (correct).
IsValidIP("127.0.0.1") returns true (correct).
IsValidIP("What's an IP address?") returns false (correct).
IsValidIP("127") returns true with first version, false with second (correct).
IsValidIP("127.0") returns true with first version, false with second (correct).
I'd use a regex.
^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$
Using named groups, it could be clearer. It is written in Ruby. I don't know C# but I guess that the regex support is complete in that language and that named groups might exist.
/(?<number>(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){0}^(\g<number>\.){3}\g<number>$/
Here's my solution:
using System.Net.NetworkInformation;
using System.Net;
/// <summary>
/// Return true if the IP address is valid.
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public bool TestIpAddress (string address)
{
PingReply reply;
Ping pingSender = new Ping ();
try
{
reply = pingSender.Send (address);
}
catch (Exception)
{
return false;
}
return reply.Status == IPStatus.Success;
}
In the internet there are several places that show you how to get an IP address. And a lot of them look like this example:
String strHostName = string.Empty;
// 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);
// 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());
}
Console.ReadLine();
With this example I get several IP addresses, but I'm only interested in getting the one that the router assigns to the computer running the program: the IP that I would give to someone if he wishes to access a shared folder in my computer for instance.
If I am not connected to a network and I am connected to the internet directly via a modem with no router then I would like to get an error. How can I see if my computer is connected to a network with C# and if it is then to get the LAN IP address.
To get local Ip Address:
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
To check if you're connected or not:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
There is a more accurate way when there are multi ip addresses available on local machine. Connect a UDP socket and read its local endpoint:
string localIP;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIP = endPoint.Address.ToString();
}
Connect on a UDP socket has the following effect: it sets the destination for Send/Recv, discards all packets from other addresses, and - which is what we use - transfers the socket into "connected" state, settings its appropriate fields. This includes checking the existence of the route to the destination according to the system's routing table and setting the local endpoint accordingly. The last part seems to be undocumented officially but it looks like an integral trait of Berkeley sockets API (a side effect of UDP "connected" state) that works reliably in both Windows and Linux across versions and distributions.
So, this method will give the local address that would be used to connect to the specified remote host. There is no real connection established, hence the specified remote ip can be unreachable.
I know this may be kicking a dead horse, but maybe this can help someone. I have looked all over the place for a way to find my local IP address, but everywhere I find it says to use:
Dns.GetHostEntry(Dns.GetHostName());
I don't like this at all because it just gets all the addresses assigned to your computer. If you have multiple network interfaces (which pretty much all computers do now-a-days) you have no idea which address goes with which network interface. After doing a bunch of research I created a function to use the NetworkInterface class and yank the information out of it. This way I can tell what type of interface it is (Ethernet, wireless, loopback, tunnel, etc.), whether it is active or not, and SOOO much more.
public string GetLocalIPv4(NetworkInterfaceType _type)
{
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
}
}
return output;
}
Now to get the IPv4 address of your Ethernet network interface call:
GetLocalIPv4(NetworkInterfaceType.Ethernet);
Or your Wireless interface:
GetLocalIPv4(NetworkInterfaceType.Wireless80211);
If you try to get an IPv4 address for a wireless interface, but your computer doesn't have a wireless card installed it will just return an empty string. Same thing with the Ethernet interface.
EDIT:
It was pointed out (thanks #NasBanov) that even though this function goes about extracting the IP address in a much better way than using Dns.GetHostEntry(Dns.GetHostName()) it doesn't do very well at supporting multiple interfaces of the same type or multiple IP addresses on a single interface. It will only return a single IP address when there may be multiple addresses assigned. To return ALL of these assigned addresses you could simply manipulate the original function to always return an array instead of a single string. For example:
public static string[] GetAllLocalIPv4(NetworkInterfaceType _type)
{
List<string> ipAddrList = new List<string>();
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
ipAddrList.Add(ip.Address.ToString());
}
}
}
}
return ipAddrList.ToArray();
}
Now this function will return ALL assigned addresses for a specific interface type. Now to get just a single string, you could use the .FirstOrDefault() extension to return the first item in the array or, if it's empty, return an empty string.
GetLocalIPv4(NetworkInterfaceType.Ethernet).FirstOrDefault();
Refactoring Mrcheif's code to leverage Linq (ie. .Net 3.0+). .
private IPAddress LocalIPAddress()
{
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
return null;
}
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
return host
.AddressList
.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
}
:)
Here is a modified version (from compman2408's one) which worked for me:
internal static string GetLocalIPv4(NetworkInterfaceType _type)
{ // Checks your IP adress from the local network connected to a gateway. This to avoid issues with double network cards
string output = ""; // default output
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) // Iterate over each network interface
{ // Find the network interface which has been provided in the arguments, break the loop if found
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{ // Fetch the properties of this adapter
IPInterfaceProperties adapterProperties = item.GetIPProperties();
// Check if the gateway adress exist, if not its most likley a virtual network or smth
if (adapterProperties.GatewayAddresses.FirstOrDefault() != null)
{ // Iterate over each available unicast adresses
foreach (UnicastIPAddressInformation ip in adapterProperties.UnicastAddresses)
{ // If the IP is a local IPv4 adress
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{ // we got a match!
output = ip.Address.ToString();
break; // break the loop!!
}
}
}
}
// Check if we got a result if so break this method
if (output != "") { break; }
}
// Return results
return output;
}
You can call this method for example like:
GetLocalIPv4(NetworkInterfaceType.Ethernet);
The change: I'm retrieving the IP from an adapter which has a gateway IP assigned to it.
Second change: I've added docstrings and break statement to make this method more efficient.
This is the best code I found to get the current IP, avoiding get VMWare host or other invalid IP address.
public string GetLocalIpAddress()
{
UnicastIPAddressInformation mostSuitableIp = null;
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
if (network.OperationalStatus != OperationalStatus.Up)
continue;
var properties = network.GetIPProperties();
if (properties.GatewayAddresses.Count == 0)
continue;
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
if (IPAddress.IsLoopback(address.Address))
continue;
if (!address.IsDnsEligible)
{
if (mostSuitableIp == null)
mostSuitableIp = address;
continue;
}
// The best IP is the IP got from DHCP server
if (address.PrefixOrigin != PrefixOrigin.Dhcp)
{
if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
mostSuitableIp = address;
continue;
}
return address.Address.ToString();
}
}
return mostSuitableIp != null
? mostSuitableIp.Address.ToString()
: "";
}
I think using LINQ is easier:
Dns.GetHostEntry(Dns.GetHostName())
.AddressList
.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
.ToString()
Other way to get IP using linq expression:
public static List<string> GetAllLocalIPv4(NetworkInterfaceType type)
{
return NetworkInterface.GetAllNetworkInterfaces()
.Where(x => x.NetworkInterfaceType == type && x.OperationalStatus == OperationalStatus.Up)
.SelectMany(x => x.GetIPProperties().UnicastAddresses)
.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(x => x.Address.ToString())
.ToList();
}
For a laugh, thought I'd try and get a single LINQ statement by using the new C# 6 null-conditional operator. Looks pretty crazy and probably horribly inefficient, but it works.
private string GetLocalIPv4(NetworkInterfaceType type = NetworkInterfaceType.Ethernet)
{
// Bastardized from: http://stackoverflow.com/a/28621250/2685650.
return NetworkInterface
.GetAllNetworkInterfaces()
.FirstOrDefault(ni =>
ni.NetworkInterfaceType == type
&& ni.OperationalStatus == OperationalStatus.Up
&& ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null
&& ni.GetIPProperties().UnicastAddresses.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork) != null
)
?.GetIPProperties()
.UnicastAddresses
.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork)
?.Address
?.ToString()
?? string.Empty;
}
Logic courtesy of Gerardo H (and by reference compman2408).
Tested with one or multiple LAN cards and Virtual machines
public static string DisplayIPAddresses()
{
string returnAddress = String.Empty;
// Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface network in networkInterfaces)
{
// Read the IP configuration for each network
IPInterfaceProperties properties = network.GetIPProperties();
if (network.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
network.OperationalStatus == OperationalStatus.Up &&
!network.Description.ToLower().Contains("virtual") &&
!network.Description.ToLower().Contains("pseudo"))
{
// Each network interface may have multiple IP addresses
foreach (IPAddressInformation address in properties.UnicastAddresses)
{
// We're only interested in IPv4 addresses for now
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
// Ignore loopback addresses (e.g., 127.0.0.1)
if (IPAddress.IsLoopback(address.Address))
continue;
returnAddress = address.Address.ToString();
Console.WriteLine(address.Address.ToString() + " (" + network.Name + " - " + network.Description + ")");
}
}
}
return returnAddress;
}
#mrcheif I found this answer today and it was very useful although it did return a wrong IP (not due to the code not working) but it gave the wrong internetwork IP when you have such things as Himachi running.
public static string localIPAddress()
{
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
localIP = ip.ToString();
string[] temp = localIP.Split('.');
if (ip.AddressFamily == AddressFamily.InterNetwork && temp[0] == "192")
{
break;
}
else
{
localIP = null;
}
}
return localIP;
}
Just an updated version of mine using LINQ:
/// <summary>
/// Gets the local Ipv4.
/// </summary>
/// <returns>The local Ipv4.</returns>
/// <param name="networkInterfaceType">Network interface type.</param>
IPAddress GetLocalIPv4(NetworkInterfaceType networkInterfaceType)
{
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces().Where(i => i.NetworkInterfaceType == networkInterfaceType && i.OperationalStatus == OperationalStatus.Up);
foreach (var networkInterface in networkInterfaces)
{
var adapterProperties = networkInterface.GetIPProperties();
if (adapterProperties.GatewayAddresses.FirstOrDefault() == null)
continue;
foreach (var ip in networkInterface.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
return ip.Address;
}
}
return null;
}
Pre requisites: you have to add System.Data.Linq reference and refer it
using System.Linq;
string ipAddress ="";
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
ipAddress = Convert.ToString(ipHostInfo.AddressList.FirstOrDefault(address => address.AddressFamily == AddressFamily.InterNetwork));
I also was struggling with obtaining the correct IP.
I tried a variety of the solutions here but none provided me the desired affect. Almost all of the conditional tests that was provided caused no address to be used.
This is what worked for me, hope it helps...
var firstAddress = (from address in NetworkInterface.GetAllNetworkInterfaces().Select(x => x.GetIPProperties()).SelectMany(x => x.UnicastAddresses).Select(x => x.Address)
where !IPAddress.IsLoopback(address) && address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
select address).FirstOrDefault();
Console.WriteLine(firstAddress);
Using these:
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Linq;
You can use a series of LINQ methods to grab the most preferred IP address.
public static bool IsIPv4(IPAddress ipa) => ipa.AddressFamily == AddressFamily.InterNetwork;
public static IPAddress GetMainIPv4() => NetworkInterface.GetAllNetworkInterfaces()
.Select((ni)=>ni.GetIPProperties())
.Where((ip)=> ip.GatewayAddresses.Where((ga) => IsIPv4(ga.Address)).Count() > 0)
.FirstOrDefault()?.UnicastAddresses?
.Where((ua) => IsIPv4(ua.Address))?.FirstOrDefault()?.Address;
This simply finds the first Network Interface that has an IPv4 Default Gateway, and gets the first IPv4 address on that interface.
Networking stacks are designed to have only one Default Gateway, and therefore the one with a Default Gateway, is the best one.
WARNING: If you have an abnormal setup where the main adapter has more than one IPv4 Address, this will grab only the first one.
(The solution to grabbing the best one in that scenario involves grabbing the Gateway IP, and checking to see which Unicast IP is in the same subnet as the Gateway IP Address, which would kill our ability to create a pretty LINQ method based solution, as well as being a LOT more code)
Updating Mrchief's answer with Linq, we will have:
public static IPAddress GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
var ipAddress= host.AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
return ipAddress;
}
This returns addresses from any interfaces that have gateway addresses and unicast addresses in two separate lists, IPV4 and IPV6.
public static (List<IPAddress> V4, List<IPAddress> V6) GetLocal()
{
List<IPAddress> foundV4 = new List<IPAddress>();
List<IPAddress> foundV6 = new List<IPAddress>();
NetworkInterface.GetAllNetworkInterfaces().ToList().ForEach(ni =>
{
if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null)
{
ni.GetIPProperties().UnicastAddresses.ToList().ForEach(ua =>
{
if (ua.Address.AddressFamily == AddressFamily.InterNetwork) foundV4.Add(ua.Address);
if (ua.Address.AddressFamily == AddressFamily.InterNetworkV6) foundV6.Add(ua.Address);
});
}
});
return (foundV4.Distinct().ToList(), foundV6.Distinct().ToList());
}
string str="";
System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(str);
IPAddress[] addr = ipEntry.AddressList;
string IP="Your Ip Address Is :->"+ addr[addr.Length - 1].ToString();
Keep in mind, in the general case you could have multiple NAT translations going on, and multiple dns servers, each operating on different NAT translation levels.
What if you have carrier grade NAT, and want to communicate with other customers of the same carrier? In the general case you never know for sure because you might appear with different host names at every NAT translation.
Obsolete gone, this works to me
public static IPAddress GetIPAddress()
{
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName()).Where(address =>
address.AddressFamily == AddressFamily.InterNetwork).First();
return ip;
}
Imports System.Net
Imports System.Net.Sockets
Function LocalIP()
Dim strHostName = Dns.GetHostName
Dim Host = Dns.GetHostEntry(strHostName)
For Each ip In Host.AddressList
If ip.AddressFamily = AddressFamily.InterNetwork Then
txtIP.Text = ip.ToString
End If
Next
Return True
End Function
Below same action
Function LocalIP()
Dim Host As String =Dns.GetHostEntry(Dns.GetHostName).AddressList(1).MapToIPv4.ToString
txtIP.Text = Host
Return True
End Function
In addition just simple code for getting Client Ip:
public static string getclientIP()
{
var HostIP = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "";
return HostIP;
}
Hope it's help you.
Modified compman2408's code to be able to iterate through each NetworkInterfaceType.
public static string GetLocalIPv4 (NetworkInterfaceType _type) {
string output = null;
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces ()) {
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up) {
foreach (UnicastIPAddressInformation ip in item.GetIPProperties ().UnicastAddresses) {
if (ip.Address.AddressFamily == AddressFamily.InterNetwork) {
output = ip.Address.ToString ();
}
}
}
}
return output;
}
And you can call it like so:
static void Main (string[] args) {
// Get all possible enum values:
var nitVals = Enum.GetValues (typeof (NetworkInterfaceType)).Cast<NetworkInterfaceType> ();
foreach (var nitVal in nitVals) {
Console.WriteLine ($"{nitVal} => {GetLocalIPv4 (nitVal) ?? "NULL"}");
}
}
There is already many of answer, but I m still contributing mine one:
public static IPAddress LocalIpAddress() {
Func<IPAddress, bool> localIpPredicate = ip =>
ip.AddressFamily == AddressFamily.InterNetwork &&
ip.ToString().StartsWith("192.168"); //check only for 16-bit block
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.LastOrDefault(localIpPredicate);
}
One liner:
public static IPAddress LocalIpAddress() => Dns.GetHostEntry(Dns.GetHostName()).AddressList.LastOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork && ip.ToString().StartsWith("192.168"));
note: Search from last because it still worked after some interfaces added into device, such as MobileHotspot,VPN or other fancy virtual adapters.
Dns.GetHostEntry(Dns.GetHostName()).AddressList[1].MapToIPv4() //returns 192.168.14.1
This is the shortest way:
Dns.GetHostEntry(
Dns.GetHostName()
).AddressList.AsEnumerable().Where(
ip=>ip.AddressFamily.Equals(AddressFamily.InterNetwork)
).FirstOrDefault().ToString()
We have Request.UserHostAddress to get the IP address in ASP.NET, but this is usually the user's ISP's IP address, not exactly the user's machine IP address who for example clicked a link. How can I get the real IP Address?
For example, in a Stack Overflow user profile it is: "Last account activity: 4 hours ago from 86.123.127.8", but my machine IP address is a bit different. How does Stack Overflow get this address?
In some web systems there is an IP address check for some purposes. For example, with a certain IP address, for every 24 hours can the user just have only 5 clicks on download links? This IP address should be unique, not for an ISP that has a huge range of clients or Internet users.
Did I understand well?
Often you will want to know the IP address of someone visiting your website. While ASP.NET has several ways to do this one of the best ways we've seen is by using the "HTTP_X_FORWARDED_FOR" of the ServerVariables collection.
Here's why...
Sometimes your visitors are behind either a proxy server or a router and the standard Request.UserHostAddress only captures the IP address of the proxy server or router. When this is the case the user's IP address is then stored in the server variable ("HTTP_X_FORWARDED_FOR").
So what we want to do is first check "HTTP_X_FORWARDED_FOR" and if that is empty we then simply return ServerVariables("REMOTE_ADDR").
While this method is not foolproof, it can lead to better results. Below is the ASP.NET code in VB.NET, taken from James Crowley's blog post "Gotcha: HTTP_X_FORWARDED_FOR returns multiple IP addresses"
C#
protected string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
VB.NET
Public Shared Function GetIPAddress() As String
Dim context As System.Web.HttpContext = System.Web.HttpContext.Current
Dim sIPAddress As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If String.IsNullOrEmpty(sIPAddress) Then
Return context.Request.ServerVariables("REMOTE_ADDR")
Else
Dim ipArray As String() = sIPAddress.Split(New [Char]() {","c})
Return ipArray(0)
End If
End Function
As others have said you can't do what you are asking. If you describe the problem you are trying to solve maybe someone can help?
E.g.
are you trying to uniquely identify your users?
Could you use a cookie, or the session ID perhaps instead of the IP address?
Edit The address you see on the server shouldn't be the ISP's address, as you say that would be a huge range. The address for a home user on broadband will be the address at their router, so every device inside the house will appear on the outside to be the same, but the router uses NAT to ensure that traffic is routed to each device correctly. For users accessing from an office environment the address may well be the same for all users. Sites that use IP address for ID run the risk of getting it very wrong - the examples you give are good ones and they often fail. For example my office is in the UK, the breakout point (where I "appear" to be on the internet) is in another country where our main IT facility is, so from my office my IP address appears to be not in the UK. For this reason I can't access UK only web content, such as the BBC iPlayer). At any given time there would be hundreds, or even thousands, of people at my company who appear to be accessing the web from the same IP address.
When you are writing server code you can never be sure what the IP address you see is referring to. Some users like it this way. Some people deliberately use a proxy or VPN to further confound you.
When you say your machine address is different to the IP address shown on StackOverflow, how are you finding out your machine address? If you are just looking locally using ipconfig or something like that I would expect it to be different for the reasons I outlined above. If you want to double check what the outside world thinks have a look at whatismyipaddress.com/.
This Wikipedia link on NAT will provide you some background on this.
UPDATE:
Thanks to Bruno Lopes. If several ip addresses could come then need to use this method:
private string GetUserIP()
{
string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipList))
{
return ipList.Split(',')[0];
}
return Request.ServerVariables["REMOTE_ADDR"];
}
If is c# see this way, is very simple
string clientIp = (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ??
Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim();
What else do you consider the user IP address? If you want the IP address of the network adapter, I'm afraid there's no possible way to do it in a Web app. If your user is behind NAT or other stuff, you can't get the IP either.
Update: While there are Web sites that use IP to limit the user (like rapidshare), they don't work correctly in NAT environments.
I think I should share my experience with you all. Well I see in some situations REMOTE_ADDR will NOT get you what you are looking for. For instance, if you have a Load Balancer behind the scene and if you are trying to get the Client's IP then you will be in trouble. I checked it with my IP masking software plus I also checked with my colleagues being in different continents. So here is my solution.
When I want to know the IP of a client, I try to pick every possible evidence so I could determine if they are unique:
Here I found another sever-var that could help you all if you want to get exact IP of the client side. so I am using : HTTP_X_CLUSTER_CLIENT_IP
HTTP_X_CLUSTER_CLIENT_IP always gets you the exact IP of the client. In any case if its not giving you the value, you should then look for HTTP_X_FORWARDED_FOR as it is the second best candidate to get you the client IP and then the REMOTE_ADDR var which may or may not return you the IP but to me having all these three is what I find the best thing to monitor them.
I hope this helps some guys.
You can use:
System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
All of the responses so far take into account the non-standardized, but very common, X-Forwarded-For header. There is a standardized Forwarded header which is a little more difficult to parse out. Some examples are as follows:
Forwarded: for="_gazonk"
Forwarded: For="[2001:db8:cafe::17]:4711"
Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43
Forwarded: for=192.0.2.43, for=198.51.100.17
I have written a class that takes both of these headers into account when determining a client's IP address.
using System;
using System.Web;
namespace Util
{
public static class IP
{
public static string GetIPAddress()
{
return GetIPAddress(new HttpRequestWrapper(HttpContext.Current.Request));
}
internal static string GetIPAddress(HttpRequestBase request)
{
// handle standardized 'Forwarded' header
string forwarded = request.Headers["Forwarded"];
if (!String.IsNullOrEmpty(forwarded))
{
foreach (string segment in forwarded.Split(',')[0].Split(';'))
{
string[] pair = segment.Trim().Split('=');
if (pair.Length == 2 && pair[0].Equals("for", StringComparison.OrdinalIgnoreCase))
{
string ip = pair[1].Trim('"');
// IPv6 addresses are always enclosed in square brackets
int left = ip.IndexOf('['), right = ip.IndexOf(']');
if (left == 0 && right > 0)
{
return ip.Substring(1, right - 1);
}
// strip port of IPv4 addresses
int colon = ip.IndexOf(':');
if (colon != -1)
{
return ip.Substring(0, colon);
}
// this will return IPv4, "unknown", and obfuscated addresses
return ip;
}
}
}
// handle non-standardized 'X-Forwarded-For' header
string xForwardedFor = request.Headers["X-Forwarded-For"];
if (!String.IsNullOrEmpty(xForwardedFor))
{
return xForwardedFor.Split(',')[0];
}
return request.UserHostAddress;
}
}
}
Below are some unit tests that I used to validate my solution:
using System.Collections.Specialized;
using System.Web;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UtilTests
{
[TestClass]
public class IPTests
{
[TestMethod]
public void TestForwardedObfuscated()
{
var request = new HttpRequestMock("for=\"_gazonk\"");
Assert.AreEqual("_gazonk", Util.IP.GetIPAddress(request));
}
[TestMethod]
public void TestForwardedIPv6()
{
var request = new HttpRequestMock("For=\"[2001:db8:cafe::17]:4711\"");
Assert.AreEqual("2001:db8:cafe::17", Util.IP.GetIPAddress(request));
}
[TestMethod]
public void TestForwardedIPv4()
{
var request = new HttpRequestMock("for=192.0.2.60;proto=http;by=203.0.113.43");
Assert.AreEqual("192.0.2.60", Util.IP.GetIPAddress(request));
}
[TestMethod]
public void TestForwardedIPv4WithPort()
{
var request = new HttpRequestMock("for=192.0.2.60:443;proto=http;by=203.0.113.43");
Assert.AreEqual("192.0.2.60", Util.IP.GetIPAddress(request));
}
[TestMethod]
public void TestForwardedMultiple()
{
var request = new HttpRequestMock("for=192.0.2.43, for=198.51.100.17");
Assert.AreEqual("192.0.2.43", Util.IP.GetIPAddress(request));
}
}
public class HttpRequestMock : HttpRequestBase
{
private NameValueCollection headers = new NameValueCollection();
public HttpRequestMock(string forwarded)
{
headers["Forwarded"] = forwarded;
}
public override NameValueCollection Headers
{
get { return this.headers; }
}
}
}
IP addresses are part of the Network layer in the "seven-layer stack". The Network layer can do whatever it wants to do with the IP address. That's what happens with a proxy server, NAT, relay, or whatever.
The Application layer should not depend on the IP address in any way. In particular, an IP Address is not meant to be an identifier of anything other than the idenfitier of one end of a network connection. As soon as a connection is closed, you should expect the IP address (of the same user) to change.
If you are using CloudFlare,
you can try this Extension Method:
public static class IPhelper
{
public static string GetIPAddress(this HttpRequest Request)
{
if (Request.Headers["CF-CONNECTING-IP"] != null) return Request.Headers["CF-CONNECTING-IP"].ToString();
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) return Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
return Request.UserHostAddress;
}
}
then
string IPAddress = Request.GetIPAddress();
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
What you can do is store the router IP of your user and also the forwarded IP and try to make it reliable using both the IPs [External Public and Internal Private]. But again after some days client may be assigned new internal IP from router but it will be more reliable.
Combining the answers from #Tony and #mangokun, I have created the following extension method:
public static class RequestExtensions
{
public static string GetIPAddress(this HttpRequest Request)
{
if (Request.Headers["CF-CONNECTING-IP"] != null) return Request.Headers["CF-CONNECTING-IP"].ToString();
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
}
return Request.UserHostAddress;
}
}
public static class Utility
{
public static string GetClientIP(this System.Web.UI.Page page)
{
string _ipList = page.Request.Headers["CF-CONNECTING-IP"].ToString();
if (!string.IsNullOrWhiteSpace(_ipList))
{
return _ipList.Split(',')[0].Trim();
}
else
{
_ipList = page.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"];
if (!string.IsNullOrWhiteSpace(_ipList))
{
return _ipList.Split(',')[0].Trim();
}
else
{
_ipList = page.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrWhiteSpace(_ipList))
{
return _ipList.Split(',')[0].Trim();
}
else
{
return page.Request.ServerVariables["REMOTE_ADDR"].ToString().Trim();
}
}
}
}
}
Use;
string _ip = this.GetClientIP();
use in ashx file
public string getIP(HttpContext c)
{
string ips = c.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ips))
{
return ips.Split(',')[0];
}
return c.Request.ServerVariables["REMOTE_ADDR"];
}
In NuGet package install Microsoft.AspNetCore.HttpOverrides
Then try:
public class ClientDeviceInfo
{
private readonly IHttpContextAccessor httpAccessor;
public ClientDeviceInfo(IHttpContextAccessor httpAccessor)
{
this.httpAccessor = httpAccessor;
}
public string GetClientLocalIpAddress()
{
return httpAccessor.HttpContext.Connection.LocalIpAddress.ToString();
}
public string GetClientRemoteIpAddress()
{
return httpAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
}
public string GetClientLocalPort()
{
return httpAccessor.HttpContext.Connection.LocalPort.ToString();
}
public string GetClientRemotePort()
{
return httpAccessor.HttpContext.Connection.RemotePort.ToString();
}
}
Its easy.Try it:
var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
just it :))
use this
Dns.GetHostEntry(Dns.GetHostName())
Hello guys Most of the codes you will find will return you server ip address not client ip address .however this code returns correct client ip address.Give it a try.
For More info just check this
https://www.youtube.com/watch?v=Nkf37DsxYjI
for getting your local ip address using javascript you can use
put this code inside your script tag
<script>
var RTCPeerConnection = /*window.RTCPeerConnection ||*/
window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
var rtc = new RTCPeerConnection({ iceServers: [] });
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', { reliable: false });
};
rtc.onicecandidate = function (evt) {
if (evt.candidate)
grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function
(k) { return addrs[k]; });
document.getElementById('list').textContent =
displayAddrs.join(" or perhaps ") || "n/a";
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})(); else
{
document.getElementById('list').innerHTML = "<code>ifconfig| grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
}
</script>
<body>
<div id="list"></div>
</body>
and For getting your public ip address you can use
put this code inside your script tag
function getIP(json) {
document.write("My public IP address is: ", json.ip);
}
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
Simply
var ip = Request.UserHostAddress;
That's all...
Try:
using System.Net;
public static string GetIpAddress() // Get IP Address
{
string ip = "";
IPHostEntry ipEntry = Dns.GetHostEntry(GetCompCode());
IPAddress[] addr = ipEntry.AddressList;
ip = addr[2].ToString();
return ip;
}
public static string GetCompCode() // Get Computer Name
{
string strHostName = "";
strHostName = Dns.GetHostName();
return strHostName;
}