This question already has answers here:
IP address in windows phone 8
(3 answers)
Closed 8 years ago.
I just need to get the current IP of the device within the local network.
Something like...
var IP = IPInformation.GetIP();
Sorry for this easy question... just can't find something.
You need to use the GetHostNames() method through NetworkInformation class (Windows.Networking.Connectivity.NetworkInformation).
You will retrieve an HostName objects Collection which contain all IP addresses (in DisplayName property)
List<string> ipAddresses = new List<string>();
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
{
//IanaInterfaceType == 71 => Wifi
//IanaInterfaceType == 6 => Ethernet (Emulator)
if (hn.IPInformation != null &&
(hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71
|| hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
{
string ipAddress = hn.DisplayName;
ipAddresses.Add(ipAddress);
}
}
Source
The IPAddresses method obtains the selected server IP address information.
It then displays the type of address family supported by the server and its
IP address in standard and byte format.
private static void IPAddresses(string server)
{
try
{
System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
// Get server related information.
IPHostEntry heserver = Dns.GetHostEntry(server);
// Loop on the AddressList
foreach (IPAddress curAdd in heserver.AddressList)
{
// Display the type of address family supported by the server. If the
// server is IPv6-enabled this value is: InternNetworkV6. If the server
// is also IPv4-enabled there will be an additional value of InterNetwork.
Console.WriteLine("AddressFamily: " + curAdd.AddressFamily.ToString());
// Display the ScopeId property in case of IPV6 addresses.
if(curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString())
Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString());
// Display the server IP address in the standard format. In
// IPv4 the format will be dotted-quad notation, in IPv6 it will be
// in in colon-hexadecimal notation.
Console.WriteLine("Address: " + curAdd.ToString());
// Display the server IP address in byte format.
Console.Write("AddressBytes: ");
Byte[] bytes = curAdd.GetAddressBytes();
for (int i = 0; i < bytes.Length; i++)
{
Console.Write(bytes[i]);
}
Console.WriteLine("\r\n");
}
}
Related
I would like to pull out the client's PC's IP address. I have tried below approaches but it always returns "::1"
1. var test = this.Request.ServerVariables.Get("REMOTE_ADDR");
2. request.UserHostAddress;
Any inputs?
You can get the I.P address like this in your Controller method:
If the client machine is behind a proxy server, we can check for the variable HTTP_X_FORWARDED_FOR:
string ip;
ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
If the IP Address is not found in the HTTP_X_FORWARDED_FOR server variable, it means that it is not using any Proxy Server and hence the IP Address is now checked in the REMOTE_ADDR server variable.
Note: On your local machine, the I.P address will be shown as ::1 which is an IPV6 loopback address (i.e. localhost). An IPV4 address would be 127.0.0.1.
This is because in such case the Client and Server both are the same machine. When the application is deployed on the server, then the result will be different.
The below code should give you collection of client IP Addresses. If not, please post your code snippet so we can verify:
public static System.Collections.Generic.IReadOnlyCollection<System.Net.IPAddress> GetIpAddresses()
{
var ipAddresses = new List<System.Net.IPAddress>();
foreach (var values in GetValues(System.Web.HttpContext.Current.Request.Headers, "X-Forwarded-For"))
{
foreach (var ipv in values.Split(new char[] { ',', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
if (ipv.Contains(":"))
{
var array = ipv.Split(':');
ipAddresses.Add(array.Length == 2 ? System.Net.IPAddress.Parse(array[0].Trim()) : System.Net.IPAddress.Parse(ipv.Trim()));
}
else
{
ipAddresses.Add(System.Net.IPAddress.Parse(ipv));
}
}
}
if (request.UserHostAddress != null)
{
if (request.UserHostAddress.Contains(":"))
{
var array = request.UserHostAddress.Split(':');
ipAddresses.Add(array.Length == 2 ? System.Net.IPAddress.Parse(array[0].Trim()) : System.Net.IPAddress.Parse(request.UserHostAddress.Trim()));
}
else
{
ipAddresses.Add(System.Net.IPAddress.Parse(request.UserHostAddress));
}
}
return ipAddresses;
}
I have a C# console application and want to be able to send an Email to a certain address if any IP addresses that are not local are found in the array, I am assuming I would use a If != statement but i cannot get anything to work. Any tips or help would be greatly appreciated.
System.Net.IPAddress[] addresslist = Dns.GetHostAddresses(C);
{
string IPs = "";
bool firstIP = true;
foreach (IPAddress ip in addresslist)
{
if (!firstIP)
{
IPs = IPs + ",";
}
IPs = IPs + ip;
firstIP = false;
}
addresslist.ToString();
if addresslist != { "10.1.20.99"} //example, have multiple IP's
then //..... this is where I am stuck
you can remove local addresses with
var filteredIPs = ipaddresslist.Where(p => !p.StartsWith("10.1"));
Then you can send a message with something like sendimportantmails(String.Join(",", filteredIPs));
I'm trying to build C# app (desktop,windows, it doesn't really matter for now), with which I would like to connect to my windows phone, using sockets, to transfer some data... I know how this can be achieved,.
When connecting through sockets I don't want to manually enter windows phone device's IP address. So I want to know if it is possible to send some HTTP request from Windows phone app with some message, and fetch that message on computer, to be sure which IP is windows phone's IP?
In other words how to know which IP address belongs to Windows phone's IP address from Bunch of Ip addresses of devices on network?
Fallow this Link from Here
Add NameSpace :
using Windows.Networking;
public static string FindIPAddress()
{
List<string> ipAddresses = new List<string>();
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
{
//IanaInterfaceType == 71 => Wifi
//IanaInterfaceType == 6 => Ethernet (Emulator)
if (hn.IPInformation != null &&
(hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71
|| hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
{
string ipAddress = hn.DisplayName;
ipAddresses.Add(ipAddress);
}
}
if (ipAddresses.Count < 1)
{
return null;
}
else if (ipAddresses.Count == 1)
{
return ipAddresses[0];
}
else
{
//if multiple suitable address were found use the last one
//(regularly the external interface of an emulated device)
return ipAddresses[ipAddresses.Count - 1];
}
}
Edit:
If I am wrong You want to get particular Windows Phone IP address from bunch of IP addresses. AFAIK you can't get like this. But I suggest you to Append some string when getting IP of Windows Phone like below which will vary from other Ip addresses by looking it self.
string IPadd = FindIPAddress();
string WPIPadd = IPadd + " - Windows phone "
MessageDialog.show(WPIPadd);
If you find any thing new apart from this Let us know. Thanks
I'm coding an application that has to get the network adapters configuration on a Windows 7 machine just like it's done in the Windows network adapters configuration panel:
So far I can get pretty much all the information I need from NetworkInterface.GetAllNetworkInterfaces() EXCEPT the subnet prefix length.
I'm aware that it can be retrieved from the C++ struc PMIB_UNICASTIPADDRESS_TABLE via OnLinkPrefixLength but I'm trying to stay in .net.
I also took a look at the Win32_NetworkAdapterConfiguration WMI class but it only seems to return the IP v4 subnet mask.
I also know that some information (not the prefix length, as far as I know) are in the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters\Interfaces\{CLSID}
I also used SysInternals ProcessMon to try to get anything usefull when saving the network adapter settings but found nothing...
So, is there any clean .NET way to get this value? (getting it from the registry wouldn't be a problem)
EDIT: Gateways
This doesn't concern the actual question, but for those who need to retrieve the entire network adapter IPv6 configuration, the IPInterfaceProperties.GatewayAdresses property only supports the IPv4 gateways. As mentionned in the answer comments below, the only way to get the entire info until .NET framework 4.5 is to call WMI.
You can do so using Win32_NetworkAdapterConfiguration. You might have overlooked it.
IPSubnet will return an array of strings. Use the second value.
I didn't have time to whip up some C# code, but I'm sure you can handle it. Using WBEMTEST, I pulled this:
instance of Win32_NetworkAdapterConfiguration
{
Caption = "[00000010] Intel(R) 82579V Gigabit Network Connection";
DatabasePath = "%SystemRoot%\\System32\\drivers\\etc";
DefaultIPGateway = {"192.168.1.1"};
Description = "Intel(R) 82579V Gigabit Network Connection";
DHCPEnabled = TRUE;
DHCPLeaseExpires = "20120808052416.000000-240";
DHCPLeaseObtained = "20120807052416.000000-240";
DHCPServer = "192.168.1.1";
DNSDomainSuffixSearchOrder = {"*REDACTED*"};
DNSEnabledForWINSResolution = FALSE;
DNSHostName = "*REDACTED*";
DNSServerSearchOrder = {"192.168.1.1"};
DomainDNSRegistrationEnabled = FALSE;
FullDNSRegistrationEnabled = TRUE;
GatewayCostMetric = {0};
Index = 10;
InterfaceIndex = 12;
IPAddress = {"192.168.1.100", "fe80::d53e:b369:629a:7f95"};
IPConnectionMetric = 10;
IPEnabled = TRUE;
IPFilterSecurityEnabled = FALSE;
IPSecPermitIPProtocols = {};
IPSecPermitTCPPorts = {};
IPSecPermitUDPPorts = {};
IPSubnet = {"255.255.255.0", "64"};
MACAddress = "*REDACTED*";
ServiceName = "e1iexpress";
SettingID = "{B102679F-36AD-4D80-9D3B-D18C7B8FBF24}";
TcpipNetbiosOptions = 0;
WINSEnableLMHostsLookup = TRUE;
WINSScopeID = "";
};
IPSubnet[1] = IPv6 subnet;
Edit: Here's some code.
StringBuilder sBuilder = new StringBuilder();
ManagementObjectCollection objects = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration").Get();
foreach (ManagementObject mObject in objects)
{
string description = (string)mObject["Description"];
string[] addresses = (string[])mObject["IPAddress"];
string[] subnets = (string[])mObject["IPSubnet"];
if (addresses == null && subnets == null)
continue;
sBuilder.AppendLine(description);
sBuilder.AppendLine(string.Empty.PadRight(description.Length,'-'));
if (addresses != null)
{
sBuilder.Append("IPv4 Address: ");
sBuilder.AppendLine(addresses[0]);
if (addresses.Length > 1)
{
sBuilder.Append("IPv6 Address: ");
sBuilder.AppendLine(addresses[1]);
}
}
if (subnets != null)
{
sBuilder.Append("IPv4 Subnet: ");
sBuilder.AppendLine(subnets[0]);
if (subnets.Length > 1)
{
sBuilder.Append("IPv6 Subnet: ");
sBuilder.AppendLine(subnets[1]);
}
}
sBuilder.AppendLine();
sBuilder.AppendLine();
}
string output = sBuilder.ToString().Trim();
MessageBox.Show(output);
and some output:
Intel(R) 82579V Gigabit Network Connection
------------------------------------------
IPv4 Address: 192.168.1.100
IPv6 Address: fe80::d53e:b369:629a:7f95
IPv4 Subnet: 255.255.255.0
IPv6 Subnet: 64
Edit: I'm just going to clarify in case somebody searches for this later. The second item isn't always the IPv6 value. IPv4 can have multiple addresses and subnets. Use Integer.TryParse on the IPSubnet array value to make sure it's an IPv6 subnet and/or use the last item.
Parse the input stream of netsh with arguments:
interface ipv6 show route
Hope this helps!
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