C# Get IP assigned by router - c#

I don't know if I'm just not searching using the right keywords, I want to be able to find the IP address of my local computer that was assigned by my router.
I was using:
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach(IPAddress ip in host.AddressList)
{
if(ip.addressfamily.tostring() == "InterNetwork")
{
return ip;
}
}
The problem is I have multiple InterNetwork ip addresses because I use virtual services, so I need to be able to identify which one was assigned by my router.

How about loopback?
if (IPAddress.IsLoopback(ip)) return ip; //localhost
Or try pinging the local machine
Ping pingSender = new Ping ();
IPAddress address = IPAddress.Loopback;
PingReply reply = pingSender.Send (address);
if (reply.Status == IPStatus.Success){..}
also this might help you
Showing The External IP-Address In C#

Related

Get local IP address of ethernet interface in C#

Is there a reliable way to get the IPv4 address of the first local Ethernet interface in C#?
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{...
This finds the local IP address associated with the Ethernet adapter but also find the Npcap Loopback Adapter (installed for use with Wireshark).
Similarly, there seems to be no way to tell the difference between the loopback address and the Ethernet address using the following code:
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{....
Any other suggestions?
The following code gets the IPv4 from the preferred interface. This should also work inside virtual machines.
using System.Net;
using System.Net.Sockets;
public static void getIPv4()
{
try
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("10.0.1.20", 1337); // doesnt matter what it connects to
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
Console.WriteLine(endPoint.Address.ToString()); //ipv4
}
}
catch (Exception)
{
Console.WriteLine("Failed"); // If no connection is found
}
}

Current IP address in use

I have a C# Win 7 desktop application that sends web requests using HttpClient. Is there any way to find out which network adapter or NetworkInterface is used to send these requests? (There could be multiple LAN, WAN and virtual adapters.)
I don't really want to use TcpClient, UdpClient or any socket level program as it more low level and user may decide to block the ports.
One route I am trying to pursue is to find IP address of the current request and then try to match it with the IP address from the NetworkInterface (using NetworkInterface.GetAllNetworkInterfaces), but HttpClient don't tell you your IP that is used to send the requests.
This is what I ended up doing:
IPAddress localAddr = null;
try
{
using (UdpClient udpClient = new UdpClient("8.8.8.8", 0)) //connect to google dns
{
localAddr = ((IPEndPoint)udpClient.Client.LocalEndPoint).Address;
udpClient.Client.Close();
udpClient.Close();
}
}
catch (SocketException sex)
{
Console.WriteLine("Failed to make UDP connection, no connection to DNS ? ");
}
//find all network interfaces
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
NetworkInterface activeAdapter = null;
foreach (NetworkInterface adapter in nics.Where(n => n.OperationalStatus == OperationalStatus.Up))
{
//wifi adapter will be 'up' only if its associated with a hotspot
IPInterfaceProperties properties = adapter.GetIPProperties();
var match = properties.UnicastAddresses.Any(a => a.Address.Equals(localAddr));
if (match)
{
activeAdapter = adapter;
break;
}
}
I had to rely on UDP client, can't find a way to get ip from HttpClient
This will get you the current 'active' network adapter that is being used to connect to internet.

Using TCP outside the LAN

I'm using the the examples provided by Microsoft to learn how to use TCP servers in C#. For TCPListener I use this http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx , and for TCPCLient I use this http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx (the examples are at the bottom of the page).
Until now I've managed to connect and send messages to other PCs connected to the same router. What I want now is to connect it to a PC outside my LAN network. How can I do that ?
I should also mention that this is the way that I use to connect PCs in LAN :
on ther server side:
public string LocalIPAddress()
{
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
break;
}
}
return localIP;
}
private void Form1_Load(object sender, EventArgs e)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
String localAddrString = LocalIPAddress();
Console.WriteLine(localAddrString);
IPAddress localAddr = IPAddress.Parse(localAddrString);
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
}
}
on the client side:
Int32 port = 13000;
String server = "192.168.X.X"; // here I manually introduce the IP provided by the server in the console
TcpClient client = new TcpClient(server, port);
I wish I could use a simple comment to give you this information but I cannot due to me only recently joining SO. You should ensure you have port forwarded (http://portforward.com/ will help you port forward), if you don't know how to you could use this easy-to-use port checker: http://www.yougetsignal.com/tools/open-ports/.

TCP Debug Error C#

public Server([Optional, DefaultParameterValue(0x6c1)] int port, [Optional, DefaultParameterValue("127.0.0.1")] string ip)
{
this.IP = IPAddress.Parse(ip);
this.Port = port;
this.listenerConnection = new TcpListener(this.IP, this.Port);
this.listenerConnection.Start();
this.listenerThread = new Thread(new ThreadStart(this.listen));
this.listenerThread.Start();
}
is the code I have, it runs fine but when I debug it, I get the message:
Specified argument was out of the range of valid values. Parameter name: port
Can anyone help?
Well, then port is out of the range of valid values, which is between IPEndPoint.MinPort and IPEndPoint.MaxPort.
Have you tried using the IPAddress of your machine? You can use the following code to obtain the IPAddress of the machine you are running the application on:
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
IPAddress localIpAddress = null;
forach(IPAddress address in host.AddressList)
{
if(address.AddressFamily == AddressFamily.InterNetwork)
{
localIpAddress = address;
}
}
TcpListener listener = new TcpListener(localIpAddress, port);
listener.Start();
Additionally, you may want to consider using a default port > 5000. As there are many ports between 0 and 5000 that are reserved or already use by services.

How to obtain Local IP?

I read this question in this thread: How to get the IP address of the server on which my C# application is running on?
But this code is not working for me:
string hostname = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(hostname);
It giving me an err on this second line in the argument:
A field initializer cannot reference
the non-static field, method, or
property.
I want to store my local IP of my machine in a string. Thats all!
public static String GetIP()
{
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if(string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
}
//This will return the collection of local IP's
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
public static bool IsLocalIpAddress(string host)
{
try
{ // get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
{
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
{
if (hostIP.Equals(localIP)) return true;
}
}
}
catch { }
return false;
}
//Call this method this will tell Is this your local Ip
IsLocalIpAddress("localhost");
In ASP.Net, you can get the IP address to which the request was made from the Request object:
string myIpAddress = Request.UserHostAddress ;
It may be an IPv4 address or an IPv6 address. To find out, parse it into an System.Net.IPAddress:
IPAddress addr = IPAddress.Parse( myIpAddress ) ;
If you're interested in the IP address of the current host, that turns into a much more complicated (interesting?) question.
Any given host (and for "host" read "individual computer") may have multiple NICs (Network Interface Card) installed. Each NIC (assuming it's attached to an IP network) has an IP address assigned to it—and likely it has both an IPv4 and an IPv6 address assigned to it.
Further, each NIC may itself be multi-homed and have additional IP addresses, either IPv4 and/or IPv6 assigned.
Then we have the IP loopback adapter, for which each host shares the same loopback addresses. For IPv4, the loopback address is defined as the entire 127/8 subnet (that is, IP addresses 127.0.0.0–127.255.255.255 are all IPv4 loopback addresses). IPv6 only assigns a single loopback address (::1).
So, from the vantage point of the host then, you need to know the context (loopback adapter or NIC? if NIC, which one? Ipv4 or IPv6?) And even then, you're not guaranteed a single IP address. You have to ask yourself what, exactly, it is you mean by "my IP address"?

Categories