I have 2 methods in my program to retrieve the IP Address of the Computer.
1st
public string GetIP1()
{
//using System.Net.Sockets;
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();
}
2nd
public string GetIP2()
{
//using System.IO;
String direction = "";
try
{
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);
}
catch(Exception){ }
return direction;
}
The 1st code returns an IP that looks like 10.xx.xx.x, and the 2nd code returns IP Address such as 121.xx.xx.xx
Why does the output of these two methods differ?
Obviously, you are behind some NAT.
So by running first code you're receiving your internal network address, and second code gives you real (external) IP address from which your network has access to Internet.
That's because second method is just call to external website determining your IP, and that website only can determine real IP address, not internal one.
In the first method, you are getting the IP Address of your internal network, so if you are behind a router, you will get an internal IP address. This is the address you would see if you ran ipconfig /all from a command prompt.
In the second method you are getting your internet (external) IP address.
Related
I am working in unity 2018. In My project I have to find my website address. I have used this code to find the web address.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
public class IpAddressFind : MonoBehaviour {
public string url="https://www.friendslearn.com";
void Start () {
GetIP(url);
}
public static string GetIP(string url) {
url = url.Replace("http://", ""); //remove http://
url = url.Replace("https://", ""); //remove https://
url = url.Substring(0, url.IndexOf("/")); //remove everything after the first /
try {
IPHostEntry hosts = Dns.GetHostEntry(url);
Debug.Log(hosts.AddressList.Length);
Debug.Log(hosts.HostName);
if(hosts.AddressList.Length > 0)
{
Debug.Log(hosts.AddressList[0].ToString());
Debug.Log("Final");
}
} catch {
Debug.Log ("Could not get IP for URL " + url);
}
return null;
}
}
This returns the CloudFlare address.
Actually my website is working in amazon EC2 and I am using nameserver in CloudFlare. When I run the code it returns the CloudFlare web address. Actually my web address is 13.37.202.259. But it returns CloudFlare's IP.
How to find my EC2 address?
EDIT:I am using old code. Is there any new API to find my IP address. In Unity 2018.
I have searched and read almost every article related to my search about how to get client ipaddress and machine name but all the codes return only server ip and name. I've tried these codes also given below, it gives my PC ip on localhost but on the server, it gives server ip and name :
string stringHostName = Dns.GetHostName();
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
and also used this method :
public string GetUserIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDER_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}enter code here
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
It gives ::1 on localhost but on the server it gives server ip only.
Kindly help me if there any way possible to get client ipaddress and machine name using C#.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
how to get my own IP address in C#?
how to get ip address of machine in c#
Hi all, I am currently developing a c# application for windows using WPF. I would like to get the computers external IP address i.e. the internet address not the local computer ip address or the local router address.
Thanks for your help.
Like stated earlier, you need an external web server. An easy call to HTTP GET with the URL "http://checkip.dyndns.org/" will get you a simple text string with your IP.
You need to have a web server sitting somewhere in the cloud so that you can call and that will be able to give you your external IP address.
Looks like this one is free.
[EDIT]
A simple request to here will get you your ip.
This is a way to get any network address (not necessarily the internet ip) as pointed out in the comments:
IPAddress host = IPAddress.None;
foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
{
host = ip;
if (ip.AddressFamily == AddressFamily.InterNetwork)
break;
}
The only way I have found is to do a httpWebRequest to http://www.whatismyip.com/automation/n09230945.asp and parse the results for the ip
You can try connecting to whatismyip.com, as shown in the code below:
using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace DreamInCode.Snippets
{
public class IpFinder
{
public static IPAddress GetExternalIp()
{
string whatIsMyIp = "http://whatismyip.com";
string getIpRegex = #"(?<=<TITLE>.*)\d*\.\d*\.\d*\.\d*(?=</TITLE>)";
WebClient wc = new WebClient();
UTF8Encoding utf8 = new UTF8Encoding();
string requestHtml = "";
try
{
requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
}
catch (WebException we)
{
// do something with exception
Console.Write(we.ToString());
}
Regex r = new Regex(getIpRegex);
Match m = r.Match(requestHtml);
IPAddress externalIp = null;
if (m.Success)
{
externalIp = IPAddress.Parse(m.Value);
}
return externalIp;
}
}
}
NOTE: The code comes from this post http://www.dreamincode.net/forums/topic/24692-showing-the-external-ip-address-in-c%23/ .
Please correct me if i am wrong. There are two types of IP -
One, the static(fixed) IP address we assign to the LAN card and second that we received from the service provider.
For ex. The IP address set for my machine is 192.168.1.10 while the IP address given by ISP is 218.64.xx.xx. (You can check this using http://www.ip2location.com/)
When I use ASP.net, i can get the IP address provided by ISP using -
HttpContext.Current.Request.UserHostAddress;
The Problem:
Now, I am working in Windows Forms environment but unable to get the IP provided by ISP, though I am able to get the fixed IP.
Can anybody help me?
Thanks for sharing your time.
You're trying to get the external IP address of your router.
You need to send an HTTP request to a third-party service which will reply with the IP address.
You can do that using the WebClient class.
For example:
///<summary>Gets the computer's external IP address from the internet.</summary>
static IPAddress GetExternalAddress() {
//<html><head><title>Current IP Check</title></head><body>Current IP Address: 129.98.193.226</body></html>
var html = new WebClient().DownloadString("http://checkip.dyndns.com/");
var ipStart = html.IndexOf(": ", StringComparison.OrdinalIgnoreCase) + 2;
return IPAddress.Parse(html.Substring(ipStart, html.IndexOf("</", ipStart, StringComparison.OrdinalIgnoreCase) - ipStart));
}
The terminology is wrong; your machine has a private IP and a public IP (not "static" and "dynamic").
To get the public IP, you need to bounce off a public server, e.g., whatismyip.org or your own server.
i found manu methods one of them is a html request to http://whatismyip.com
public static IPAddress GetExternalIp()
{
string whatIsMyIp = "http://whatismyip.com";
string getIpRegex = #"(?<=<TITLE>.*)\d*\.\d*\.\d*\.\d*(?=</TITLE>)";
WebClient wc = new WebClient();
UTF8Encoding utf8 = new UTF8Encoding();
string requestHtml = "";
try
{
requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
}
catch (WebException we)
{
// do something with exception
Console.Write(we.ToString());
}
Regex r = new Regex(getIpRegex);
Match m = r.Match(requestHtml);
IPAddress externalIp = null;
if (m.Success)
{
externalIp = IPAddress.Parse(m.Value);
}
return externalIp;
}
or use
IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());
Console.Write(IPHost.AddressList[0].ToString());
you can try this in the System.Net namespace:
Dns.GetHostAddresses(Dns.GetHostName())
try with this (using System.Net):
IPHostEntry he = Dns.GetHostByName(Dns.GetHostName());
var s = he.AddressList[0].ToString(); // returns IP address
Is there a 1 line method to get the IP Address of the server?
Thanks
Request.ServerVariables["LOCAL_ADDR"];
From the docs:
Returns the server address on which the request came in. This is important on computers where there can be multiple IP addresses bound to the computer, and you want to find out which address the request used.
This is distinct from the Remote addresses which relate to the client machine.
From searching the net I found following code: (I couldn't find a single line method there)
string myHost = System.Net.Dns.GetHostName();
// Show the hostname
MessageBox.Show(myHost);
// Get the IP from the host name
string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[index].ToString();
// Show the IP
MessageBox.Show(myIP);
-> where index is the index of your ip address host (ie. network connection).
Code from: http://www.geekpedia.com/tutorial149_Get-the-IP-address-in-a-Windows-application.html
As other(s) have posted, System.Net.Dns.GetHostEntry is the way to go. When you access the AddressList property, you'll want to take the AddressFamily property into account, as it could return both IPv4 AND IPv6 results.
This method will return your machine public IP address when run this code on your PC and when you deploy your application on server will return Server IP address.
public static string Getpublicip()
{
try
{
string externalIP = "";
var request = (HttpWebRequest)WebRequest.Create("http://icanhazip.com.ipaddress.com/");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
externalIP = new WebClient().DownloadString("http://icanhazip.com");
return externalIP;
}
catch (Exception e)
{
return "null";
}
}