C# check if ip address matches adapter ip address settings - c#

I'm totally out of C# hence hanging a little here. I stole the code from https://stackoverflow.com/a/13175574 to read out all adapter settings available on the pc. So far so good.
What I need now is a way to check, which of the adapters are able to connect to an attached device with a given ip address.
I'd like to have a function like "bool CheckIfValidIP(IPAddress adapter, IPAddress IPv4Mask, IPAddress address)".
Can you help me here? I know it's pretty trivial :-/
Edit:
public static class IPAddressExtensions
{
public static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask)
{
byte[] ipAdressBytes = address.GetAddressBytes();
byte[] subnetMaskBytes = subnetMask.GetAddressBytes();
if (ipAdressBytes.Length != subnetMaskBytes.Length)
throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
byte[] broadcastAddress = new byte[ipAdressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++)
{
broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));
}
return new IPAddress(broadcastAddress);
}
public static bool IsInSameSubnet(IPAddress address2, IPAddress address, IPAddress subnetMask)
{
IPAddress network1 = address.GetNetworkAddress(subnetMask);
IPAddress network2 = address2.GetNetworkAddress(subnetMask);
return network1.Equals(network2);
}
}
This code shall do it. Is it safe to use?

A very simple example to get you in the right direction, this is created in .Net core 6:
using System.Net.NetworkInformation;
using System.Net.Sockets;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
var adaptertList = new List<NetworkInterface>();
const string IpAddressToValidate = "192.168.1.1"; //Both of these values can be retrieved from appsetting.json file
const string IpV4MaskToValidate = "255.255.255.0";
adaptertList = GetValidAdapterList(interfaces);
List<NetworkInterface> GetValidAdapterList(NetworkInterface[] interfaces) {
var adaptertList = new List<NetworkInterface>();
foreach (var adapter in interfaces) {
var ipProps = adapter.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses) {
if ((adapter.OperationalStatus == OperationalStatus.Up)//Check for any conditions appropriate to your case
&& (ip.Address.AddressFamily == AddressFamily.InterNetwork)) {
if (CheckIsValidIP(ip.Address.ToString(), ip.IPv4Mask.ToString(), IpAddressToValidate, IpV4MaskToValidate)) {
adaptertList.Add(adapter);
continue;//If IP found exit the loop, as the adapter is already added
}
}
}
}
return adaptertList;
}
bool CheckIsValidIP(string ipAddress, string ipV4Mask, string validIpAddress, string validIpV4Mask) {
return (ipAddress == validIpAddress && ipV4Mask == validIpV4Mask);
}
This code will return a list of all the adapter in the machine that meet the Ip address and ipv4mask criteria.

Related

C# Local IP is not correct with multiple Ethernet

I need to get the Local IP address of PC but if pc is connected to multiple network the ip is not correct.
I'm using:
public static string GetIPAddress()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
Like:
I need get the local ip of adapter with internet or all local ip address.
I can see 2 options:
option 1
loop trough all interfaces using System.Net.NetworkInformation:
static List<IPAddress> GetIpAddress()
{
List<IPAddress> AllIps = new List<IPAddress>();
foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties properties = netif.GetIPProperties();
foreach (IPAddressInformation unicast in properties.UnicastAddresses)
{
AllIps.Add(unicast.Address);
Console.WriteLine(unicast.Address);
}
}
return AllIps;
}
option 2
find the default gateway to the internet, then match the default gateway address to the interface addresses you found:
public static IPAddress GetDefaultGateway()
{
IPAddress result = null;
var cards = NetworkInterface.GetAllNetworkInterfaces().ToList();
if (cards.Any())
{
foreach (var card in cards)
{
var props = card.GetIPProperties();
if (props == null)
continue;
var gateways = props.GatewayAddresses;
if (!gateways.Any())
continue;
var gateway =
gateways.FirstOrDefault(g => g.Address.AddressFamily.ToString() == "InterNetwork");
if (gateway == null)
continue;
result = gateway.Address;
break;
};
}
return result;
}
now you can combine the 2 options in order to find the interface that is connected to the internet. here is my suggestion to match the default gateway to the correct adapter address. you can also determine the IP address classes
using the IpClass Enumeration that is written in the code i have added:
static void Main(string[] args)
{
// find all interfaces ip adressess
var allAdaptersIp = GetIpAddress();
// find the default gateway
var dg = GetDefaultGateway();
// match the default gateway to the host address => the interface that is connected to the internet => that print host address
Console.WriteLine("ip address that will route you to the world: " + GetInterNetworkHostIp(ref allAdaptersIp, dg, IpClass.ClassC));
Console.ReadLine();
}
enum IpClass
{
ClassA,
ClassB,
ClassC
}
static string GetInterNetworkHostIp(ref List<IPAddress> adapters, IPAddress dg, IpClass ipclassenum)
{
string networkAddress = "";
var result = "" ;
switch (ipclassenum)
{
case IpClass.ClassA:
networkAddress = dg.ToString().Substring(0, dg.ToString().Length - dg.ToString().LastIndexOf(".") );
break;
case IpClass.ClassB:
networkAddress = dg.ToString().Substring(0, dg.ToString().Length - dg.ToString().IndexOf(".",3));
break;
case IpClass.ClassC:
networkAddress = dg.ToString().Substring(0, dg.ToString().Length- dg.ToString().IndexOf(".") );
break;
default:
break;
}
foreach (IPAddress ip in adapters)
{
if (ip.ToString().Contains(networkAddress))
{
result = ip.ToString();
break;
}
}
if (result == "")
result = "no ip was found";
return result;
}

How to get the public IP address of a user in C#

I want the public IP address of the client who is using my website.
The code below is showing the local IP in the LAN, but I want the public IP of the client.
//get mac address
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
}
// To Get IP Address
string IPHost = Dns.GetHostName();
string IP = Dns.GetHostByName(IPHost).AddressList[0].ToString();
Output:
Ip Address : 192.168.1.7
Please help me to get the public IP address.
This is what I use:
protected void GetUser_IP()
{
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
uip.Text = "Your IP is: " + VisitorsIPAddr;
}
"uip" is the name of the label in the aspx page that shows the user IP.
You can use "HTTP_X_FORWARDED_FOR" or "REMOTE_ADDR" header attribute.
Refer method GetVisitorIPAddress from Machine Syntax blog .
/// <summary>
/// method to get Client ip address
/// </summary>
/// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
/// <returns></returns>
public static string GetVisitorIPAddress(bool GetLan = false)
{
string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
{
GetLan = true;
visitorIPAddress = string.Empty;
}
if (GetLan && string.IsNullOrEmpty(visitorIPAddress))
{
//This is for Local(LAN) Connected ID Address
string stringHostName = Dns.GetHostName();
//Get Ip Host Entry
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
//Get Ip Address From The Ip Host Entry Address List
IPAddress[] arrIpAddress = ipHostEntries.AddressList;
try
{
visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
}
catch
{
try
{
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
try
{
arrIpAddress = Dns.GetHostAddresses(stringHostName);
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
visitorIPAddress = "127.0.0.1";
}
}
}
}
return visitorIPAddress;
}
Combination of all of these suggestions, and the reasons behind them. Feel free to add more test cases too. If getting the client IP is of utmost importance, than you might wan to get all of theses are run some comparisons on which result might be more accurate.
Simple check of all suggestions in this thread plus some of my own code...
using System.IO;
using System.Net;
public string GetUserIP()
{
string strIP = String.Empty;
HttpRequest httpReq = HttpContext.Current.Request;
//test for non-standard proxy server designations of client's IP
if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
{
strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
}
else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
//test for host address reported by the server
else if
(
//if exists
(httpReq.UserHostAddress.Length != 0)
&&
//and if not localhost IPV6 or localhost name
((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
)
{
strIP = httpReq.UserHostAddress;
}
//finally, if all else fails, get the IP from a web scrape of another server
else
{
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
strIP = sr.ReadToEnd();
}
//scrape ip from the html
int i1 = strIP.IndexOf("Address: ") + 9;
int i2 = strIP.LastIndexOf("</body>");
strIP = strIP.Substring(i1, i2 - i1);
}
return strIP;
}
That code gets you the IP address of your server not the address of the client who is accessing your website. Use the HttpContext.Current.Request.UserHostAddress property to the client's IP address.
For Web Applications ( ASP.NET MVC and WebForm )
/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
var context = System.Web.HttpContext.Current;
string ip = String.Empty;
if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
ip = context.Request.UserHostAddress;
if (ip == "::1")
ip = "127.0.0.1";
return ip;
}
For Windows Applications ( Windows Form, Console, Windows Service , ... )
static void Main(string[] args)
{
HTTPGet req = new HTTPGet();
req.Request("http://checkip.dyndns.org");
string[] a = req.ResponseBody.Split(':');
string a2 = a[1].Substring(1);
string[] a3=a2.Split('<');
string a4 = a3[0];
Console.WriteLine(a4);
Console.ReadLine();
}
So many of these code snippets are really big and could confuse new programmers looking for help.
How about this simple and compact code to fetch the IP address of the visitor?
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"];
}
Simple, short and compact.
I have an extension method:
public static string GetIp(this HttpContextBase context)
{
if (context == null || context.Request == null)
return string.Empty;
return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
?? context.Request.UserHostAddress;
}
Note: "HTTP_X_FORWARDED_FOR" is for ip behind proxy. context.Request.UserHostAddress is identical to "REMOTE_ADDR".
But bear in mind it is not necessary the actual IP though.
Sources:
IIS Server Variables
Link
My version handles both ASP.NET or LAN IPs:
/**
* Get visitor's ip address.
*/
public static string GetVisitorIp() {
string ip = null;
if (HttpContext.Current != null) { // ASP.NET
ip = string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
? HttpContext.Current.Request.UserHostAddress
: HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
if (string.IsNullOrEmpty(ip) || ip.Trim() == "::1") { // still can't decide or is LAN
var lan = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(r => r.AddressFamily == AddressFamily.InterNetwork);
ip = lan == null ? string.Empty : lan.ToString();
}
return ip;
}
private string GetClientIpaddress()
{
string ipAddress = string.Empty;
ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipAddress == "" || ipAddress == null)
{
ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
return ipAddress;
}
else
{
return ipAddress;
}
}
On MVC 5 you can use this:
string cIpAddress = Request.UserHostAddress; //Gets the client ip address
or
string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address
In MVC IP can be obtained by the following Code
string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
just use this..................
public string GetIP()
{
string externalIP = "";
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
return externalIP;
}
We connect to servers that give us our external IP address and try to parse the IP from returning HTML pages. But when servers make small changes on these pages or remove them, these methods stop working properly.
Here is a method that takes the external IP address using a server which has been alive for years and returns a simple response rapidly...
https://www.codeproject.com/Tips/452024/Getting-the-External-IP-Address
Private string getExternalIp()
{
try
{
string externalIP;
externalIP = (new
WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
catch { return null; }
}
VB.NET
Imports System.Net
Private Function GetExternalIp() As String
Try
Dim ExternalIP As String
ExternalIP = (New WebClient()).DownloadString("http://checkip.dyndns.org/")
ExternalIP = (New Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) _
.Matches(ExternalIP)(0).ToString()
Return ExternalIP
Catch
Return Nothing
End Try
End Function
lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();
You can download xNet at: https://drive.google.com/open?id=1fmUosINo8hnDWY6s4IV4rDnHKLizX-Hq
First, you need import xNet, code:
using xNet;
Code:
void LoadpublicIP()
{
HttpRequest httprequest = new HttpRequest();
String HTML5 = httprequest.Get("https://whoer.net/").ToString();
MatchCollection collect = Regex.Matches(HTML5, #"<strong data-clipboard-target="".your-ip(.*?)</strong>", RegexOptions.Singleline);
foreach (Match match in collect)
{
var val = Regex.Matches(match.Value, #"(?<ip>(\d|\.)+)");
foreach (Match m in val)
{
richTextBox1.Text = m.Groups[2].Value;
}
}
}

How do you get host's broadcast address of the default network adapter? C#

Let's say that I want to send an udp message to every host in my subnet (and then receive an udp message from any host in my subnet):
at the moment I do:
IPAddress broadcast = IPAddress.Parse("192.168.1.255");
but of course I want this to be done dinamically in the event that the subnet is different from 192.168.1/24. I've tried with:
IPAddress broadcast = IPAddress.Broadcast;
but IPAddress.Broadcast represents "255.255.255.255" which can't be used to send messages (it throws an exception)...so:
how do I get the local network adapter broadcast address (or netmask of course)?
THIS IS THE FINAL SOLUTION I CAME UP WITH
public IPAddress getBroadcastIP()
{
IPAddress maskIP = getHostMask();
IPAddress hostIP = getHostIP();
if (maskIP==null || hostIP == null)
return null;
byte[] complementedMaskBytes = new byte[4];
byte[] broadcastIPBytes = new byte[4];
for (int i = 0; i < 4; i++)
{
complementedMaskBytes[i] = (byte) ~ (maskIP.GetAddressBytes().ElementAt(i));
broadcastIPBytes[i] = (byte) ((hostIP.GetAddressBytes().ElementAt(i))|complementedMaskBytes[i]);
}
return new IPAddress(broadcastIPBytes);
}
private IPAddress getHostMask()
{
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface Interface in Interfaces)
{
IPAddress hostIP = getHostIP();
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
if (UnicatIPInfo.Address.ToString() == hostIP.ToString())
{
return UnicatIPInfo.IPv4Mask;
}
}
}
return null;
}
private IPAddress getHostIP()
{
foreach (IPAddress ip in (Dns.GetHostEntry(Dns.GetHostName())).AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip;
}
return null;
}
If you get the local IP and subnet, it should be no problem to calculate.
Something like this maybe?
using System;
using System.Net.NetworkInformation;
public class test
{
public static void Main()
{
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface Interface in Interfaces)
{
if(Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
if (Interface.OperationalStatus != OperationalStatus.Up) continue;
Console.WriteLine(Interface.Description);
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach(UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
Console.WriteLine("\tIP Address is {0}", UnicatIPInfo.Address);
Console.WriteLine("\tSubnet Mask is {0}", UnicatIPInfo.IPv4Mask);
}
}
}
}
How to calculate the IP range when the IP address and the netmask is given? Should give you the rest of it.

How to identify if user is inside or outside my network in ASP.NET

I have to identify if the acess is comming from my local network (the same network of my server) or is comming from the internet. (using ASP.NET)
I'm planning to create a extra security.. I mean, if the access is comming from outside, I will "allow" specifics users only.
I tried to search on the web but I found nothing.
Thanks in advance.
you can do something like this (dummy code)
private bool IsInSameSubnet(IPAddress address, IPAddress address2, IPAddress subnetMask) {
bool isInSameSubnet = false;
IPAddress network1 = GetNetworkAddress(address, subnetMask);
IPAddress network2 = GetNetworkAddress(address2, subnetMask);
if (network1 != null && network2 != null) {
isInSameSubnet = network1.Equals(network2);
}
return isInSameSubnet;
}
private IPAddress GetNetworkAddress(IPAddress address, IPAddress subnetMask) {
byte[] ipAdressBytes = address.GetAddressBytes();
byte[] subnetMaskBytes = subnetMask.GetAddressBytes();
if (ipAdressBytes.Length != subnetMaskBytes.Length)
return null;
//throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
byte[] broadcastAddress = new byte[ipAdressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++) {
broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));
}
return new IPAddress(broadcastAddress);
}
where IsInSameSubnet address checks if it is in the same network
example :
string computerIP = getIP();
IPAddress ip1 = IPAddress.Parse(computerIP);
IPAddress ip2 = IPAddress.Parse("192.168.0.0");
IPAddress subnetMask = IPAddress.Parse("255.255.0.0");
and getIp method
public static string getIP() {
//if user behind proxy this should get it
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ip != null && ip.Split(',').Count() > 1) {
//if (ip.Split(',').Count() > 1)
ip = ip.Split(',')[0];
}
//if user not behind proxy this should do it
if (ip == null)
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
return ip;
}

What is my internet accessing IP

I have two lan cards installed in my pc. One is for internet connection and another for share the internet to client machines. I am getting my IP with this code:
IPHostEntry HosyEntry = Dns.GetHostEntry((Dns.GetHostName()));
foreach (IPAddress ip in HosyEntry.AddressList)
{
trackingIp = ip.ToString();
textBox1.Text += trackingIp + ",";
}
How can I find which one my internet connecting IP (I dont want to do it by text processing)?
The best way to get this information is to use WMI, this program outputs the IP addresses for the network adapter that's registered for the network destination "0.0.0.0", which is for all intents and purposes "not my network", aka "the internet" (Note: I'm not a networking expert so that may not be entirely correct).
using System;
using System.Management;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_IP4RouteTable WHERE Destination=\"0.0.0.0\"");
int interfaceIndex = -1;
foreach (var item in searcher.Get())
{
interfaceIndex = Convert.ToInt32(item["InterfaceIndex"]);
}
searcher = new ManagementObjectSearcher("root\\CIMV2",
string.Format("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE InterfaceIndex={0}", interfaceIndex));
foreach (var item in searcher.Get())
{
var ipAddresses = (string[])item["IPAddress"];
foreach (var ipAddress in ipAddresses)
{
Console.WriteLine(ipAddress);
}
}
}
}
}
Ok. I wrote 2 methods.
First method is faster but require to use a socket.
It tries to connect to remote host using each local IP.
Second methos is slower and did not use sockets. It connects to remote host (get response, waste some traffic) and look for local IP in the active connections table.
Code is draft so double check it.
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
class Program
{
public static List<IPAddress> GetInternetIPAddressUsingSocket(string internetHostName, int port)
{
// get remote host IP. Will throw SocketExeption on invalid hosts
IPHostEntry remoteHostEntry = Dns.GetHostEntry(internetHostName);
IPEndPoint remoteEndpoint = new IPEndPoint(remoteHostEntry.AddressList[0], port);
// Get all locals IP
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
var internetIPs = new List<IPAddress>();
// try to connect using each IP
foreach (IPAddress ip in hostEntry.AddressList) {
IPEndPoint localEndpoint = new IPEndPoint(ip, 80);
bool endpointIsOK = true;
try {
using (Socket socket = new Socket(localEndpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) {
socket.Connect(remoteEndpoint);
}
}
catch (Exception) {
endpointIsOK = false;
}
if (endpointIsOK) {
internetIPs.Add(ip); // or you can return first IP that was found as single result.
}
}
return internetIPs;
}
public static HashSet <IPAddress> GetInternetIPAddress(string internetHostName)
{
// get remote IPs
IPHostEntry remoteMachineHostEntry = Dns.GetHostEntry(internetHostName);
var internetIPs = new HashSet<IPAddress>();
// connect and search for local IP
WebRequest request = HttpWebRequest.Create("http://" + internetHostName);
using (WebResponse response = request.GetResponse()) {
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
response.Close();
foreach (TcpConnectionInformation t in connections) {
if (t.State != TcpState.Established) {
continue;
}
bool isEndpointFound = false;
foreach (IPAddress ip in remoteMachineHostEntry.AddressList) {
if (ip.Equals(t.RemoteEndPoint.Address)) {
isEndpointFound = true;
break;
}
}
if (isEndpointFound) {
internetIPs.Add(t.LocalEndPoint.Address);
}
}
}
return internetIPs;
}
static void Main(string[] args)
{
List<IPAddress> internetIP = GetInternetIPAddressUsingSocket("google.com", 80);
foreach (IPAddress ip in internetIP) {
Console.WriteLine(ip);
}
Console.WriteLine("======");
HashSet<IPAddress> internetIP2 = GetInternetIPAddress("google.com");
foreach (IPAddress ip in internetIP2) {
Console.WriteLine(ip);
}
Console.WriteLine("Press any key");
Console.ReadKey(true);
}
}
}
NICs that route to the Internet have a gateway. The benefit of this approach is that you don't have to do a DNS lookup or bounce of a web server.
Here's some code that displays local IPs for a NIC that has a valid gateway:
/// <summary>
/// This utility function displays all the IP addresses that likely route to the Internet.
/// </summary>
public static void DisplayInternetIPAddresses()
{
var sb = new StringBuilder();
// Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
// Read the IP configuration for each network
var properties = network.GetIPProperties();
// Only consider those with valid gateways
var gateways = properties.GatewayAddresses.Select(x => x.Address).Where(
x => !x.Equals(IPAddress.Any) && !x.Equals(IPAddress.None) && !x.Equals(IPAddress.Loopback) &&
!x.Equals(IPAddress.IPv6Any) && !x.Equals(IPAddress.IPv6None) && !x.Equals(IPAddress.IPv6Loopback));
if (gateways.Count() < 1)
continue;
// Each network interface may have multiple IP addresses
foreach (var address in properties.UnicastAddresses)
{
// Comment these next two lines to show IPv6 addresses too
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
sb.AppendLine(address.Address + " (" + network.Name + ")");
}
}
MessageBox.Show(sb.ToString());
}
You could use http://www.whatismyip.org/ it echos back your IP.

Categories

Resources