Get Public client IP in C#/.net without external service - c#

How i get public client IP in C# without external api/service
I tried use this code. But, not success.
string ipAddress = Response.HttpContext.Connection.RemoteIpAddress.ToString();
if(ipAddress == "::1")
{
ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[1].ToString();
}
Console.WriteLine(ipAddress);

on ASP.NET Follow This Method:
Public string GetIp()  
{  
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
if (string.IsNullOrEmpty(ip))  
{  
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];  
}  
return ip;  
} 
otherwise use below method:
Public string GetIp()  {
string IPAddress = "";
IPHostEntry Host = default(IPHostEntry);
string Hostname = null;
Hostname = System.Environment.MachineName;
Host = Dns.GetHostEntry(Hostname);
foreach (IPAddress IP in Host.AddressList)
{
if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
IPAddress = Convert.ToString(IP);
}
}
return IPAddress;
}
Please up-vote if you found this helpful.

Related

How to get Local Router Address[Not IPV4 address of device] in Xamarin

I have tried below code but it keeps on giving the me iPhone(ie.Device) IP Address. But I want to get a ROUTER IP ADDRESS
public string GetIPAddress()
{
String ipAddress = "";
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine(netInterface);
if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses)
{
if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = addrInfo.Address.ToString();
}
}
}
}
iPhone IPAddress: 192.168.0.19
Router: 192.168.0.1
I can do the Hacky way of removing the '9' from the last set of IP address. But I don't want to do this.
You can use the following code to get a ROUTER IP ADDRESS(Gateway address) from Android side.
Create a DependenceService in Forms folder.
public interface INetServices
{
string ConvertGateway();
}
Then achieve this interface in the android folder.
[assembly: Dependency(typeof(NetService))]
namespace Forms.Droid
{
class NetService: INetServices
{
[Obsolete]
public string ConvertGateway()
{
WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Service.WifiService);
int ip = wifiManager.ConnectionInfo.IpAddress;
int gateway = wifiManager.DhcpInfo.Gateway;
IPAddress ipAddr = new IPAddress(ip);
IPAddress gatewayAddr = new IPAddress(gateway);
return gatewayAddr.ToString();
}
}
}
And add following permission in the AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
In the Xamarin forms, you can get ROUTER IP ADDRESS like following code.
var gatewayAddress = DependencyService.Get<INetServices>().ConvertGateway();            
Console.WriteLine(gatewayAddress);

Get Client external IP or Client LAN IP

public static string GetClientExternalIp()
{
HttpContext context = 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"];
}
I am struggling with the above code snippet, i want to get the client external IP address like what you see when browse to http://checkip.dyndns.org but above snippet returns the IP address of the Server. What i need is the IP address of the LAN the client is connecting from NOT the web server IP.
Use HttpRequest.UserHostAddress
HttpContext.Current.Request.UserHostAddress;
I use the above line of code and it returns the clients IP address.
Try this..
This works for me.
By using this method you can get the client IP address instead of Server IP.
public static string GetClientIP()
{
try
{
string VisitorsIPAddress = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddress = HttpContext.Current.Request.UserHostAddress;
}
return VisitorsIPAddress;
}
catch (Exception)
{
return null;
}
}

Get IP address of client machine

I am trying to get the IP address of client machine using C#. I am using the below code to get the IP address :
string IPAddress = HttpContext.Current.Request.UserHostAddress;
But it is giving me the response in encoded format i.e fe80::ed13:dee2:127e:1264%13
How can I get the actual IP address? Any one faced this issue please share some idea.
C#
string IPAddress = GetIPAddress();
public string GetIPAddress()
{
IPHostEntry Host = default(IPHostEntry);
string Hostname = null;
Hostname = System.Environment.MachineName;
Host = Dns.GetHostEntry(Hostname);
foreach (IPAddress IP in Host.AddressList) {
if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
IPAddress = Convert.ToString(IP);
}
}
return IPAddress;
}
VB.net
Dim Host As IPHostEntry
Dim Hostname As String
Hostname = My.Computer.Name
Host = Dns.GetHostEntry(Hostname)
For Each IP As IPAddress In Host.AddressList
If IP.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
IPAddress = Convert.ToString(IP)
End If
Next
Return IPAddress
Hope this helps
private string GetUserIP()
{
return Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Request.ServerVariables["REMOTE_ADDR"];
}
You may get several ip address, so can split them as-
private string GetUserIP()
{
string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipList))
{
return ipList.Split(',')[0];
}
return Request.ServerVariables["REMOTE_ADDR"];
}
try using this
string ip=System.Net.Dns.GetHostEntry
(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
In my project it's required to get the local PC IP. So i use it
Please try the below code
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
string ip = addr[1].ToString();

Getting the ip adress of the user connected to asp application

I'd like to know how to get the IP of the user connected to my application ( asp.net mvc4) .
I tried:
IPHostEntry ipHostEntry = Dns.GetHostByName(Dns.GetHostName());
IPAddress ipAddress = ipHostEntry.AddressList[0];
But it didn't work.
So how can I modify the snippet to get the Ip` or the connected user?
Here's the converted C# code from the similar question #jamieHennerley suggested.
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"];
}

Get IPv4 addresses from Dns.GetHostEntry()

I've got some code here that works great on IPv4 machines, but on our build server (an IPv6) it fails. In a nutshell:
IPHostEntry ipHostEntry = Dns.GetHostEntry(string.Empty);
The documentation for GetHostEntry says that passing in string.Empty will get you the IPv4 address of the localhost. This is what I want. The problem is that it's returning the string "::1:" on our IPv6 machine, which I believe is the IPv6 address.
Pinging the machine from any other IPv4 machine gives a good IPv4 address... and doing a "ping -4 machinename" from itself gives the correct IPv4 address.... but pinging it regularly from itself gives "::1:".
How can I get the IPv4 for this machine, from itself?
Have you looked at all the addresses in the return, discard the ones of family InterNetworkV6 and retain only the IPv4 ones?
To find all local IPv4 addresses:
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
or use Array.Find or Array.FindLast if you just want one.
IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
IPAddress ipAddress = ipHostInfo.AddressList
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
public Form1()
{
InitializeComponent();
string myHost = System.Net.Dns.GetHostName();
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
}
Declare myIP and myHost in public Variable
and use in any function of the form.
public static string GetIPAddress(string hostname)
{
IPHostEntry host;
host = Dns.GetHostEntry(hostname);
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
//System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip);
return ip.ToString();
}
}
return string.Empty;
}
To find all valid address list this is the code I have used
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
You can get all IPv4 address from the DNS using this code:
IPs[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
address => address.AddressFamily == AddressFamily.InterNetwork);
IPv6
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()
IPv4
lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(1).ToString()

Categories