Get local IP address of ethernet interface in C# - 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
}
}

Related

How do you get the IP address of a server (not a webserver) but a TCP server created on a wifi module in Xamarin.Forms

I need to get the IP address of a Wi-Fi module, running a TCP server. The application will open the WiFi connections settings page to allow the user to connect to the Wi-Fi module's created network (requiring the password to be entered)- see attached picture. The server (Wi-FI module) IP address is 172.1.4.155 (for example) but when I try to get the IP address in Xamarin.Forms using GetLocalIPAddress() (attached below), the address it returns is the local IP address of the device (Phone)- 172.1.4.55 (for example). I need to be able to get the IP address programmatically without a user input in an Application.
Is there any way to get the IP address of the (external) non-device specific IP address? I assume the returned IP address of the phone is the DHCP assigned IP address. I need to get the server IP address as it is essential to establish a TCP socket connection between the phone and the WiFi module. I have been trying to look for a solution without any success for a few days now so any help/suggestions or examples will be greatly appreciated.
The code below is the GetLocalIPAddress() function to get the IP address.
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
//return "";
}
//throw new Exception("Local IP Address Not Found!");
return "None";
}
How to Read IP Address in XAMARIN Form, i have Created the DependencyServices in both IOS and Android projects and getting a proper IP address. Below is code to get IP address.
In PCL Project
public interface IIPAddressManager
{
String GetIPAddress();
}
In IOS Project
[assembly: Dependency(typeof(YourAppNamespace.iOSUnified.iOS.DependencyServices.IPAddressManager))]
namespace YourAppNamespace.iOSUnified.iOS.DependencyServices
{
class IPAddressManager : IIPAddressManager
{
public string GetIPAddress()
{
String ipAddress = "";
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
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();
}
}
}
}
return ipAddress;
}
}
}
In Android Project.
[assembly: Dependency(typeof(YourAppNamespace.Android.Android.DependencyServices.IPAddressManager))]
namespace YourAppNamespace.Android.Android.DependencyServices
{
class IPAddressManager : IIPAddressManager
{
public string GetIPAddress()
{
IPAddress[] adresses = Dns.GetHostAddresses(Dns.GetHostName());
if (adresses !=null && adresses[0] != null)
{
return adresses[0].ToString();
}
else
{
return null;
}
}
}
}
Then call a DependencyServices in UI project.
string ipaddress = DependencyService.Get<IIPAddressManager>().GetIPAddress

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.

C# Get IP assigned by router

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#

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/.

Socket.Bind and Connect using local addresses

To test my server/client application, where each client is known by its IP address, I created several network adapters (see How to Create a Virtual Network Adapter in .NET?). Both 192.168.0.10 and 11 now correspond to local ethernet adaptors (10 being the "real" one, 11 being a loopback adapter).
The client can Connect itself to the server as long as it doesn't Bind its socket to a specific address. But if it does, the server doesn't notice anything and a timeout occurs in the client (I want to use Bind as for security reasons the server automatically detects which client is connecting itself by looking at the IP address of the remote end point of the new connection: the server will drop the connection at once if it doesn't know the IP address - previously I was using several virtual machines, but it uses a lot more RAM and is less practical to use).
Here's the code in my server, listening eg on 192.168.0.10:1234
IPEndPoint myEP = new IPEndPoint(myAddress, myPort);
Socket listeningSocket = new Socket(myAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listeningSocket.Bind(myEP);
listeningSocket.Listen(50);
Socket acceptedSocket = listeningSocket.Accept();
Here's the code in my client, binding eg to 192.168.0.11 (any port) and connecting to 192.168.0.10:1234
Socket socket = new Socket(svrAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(myAddress, 0)); // Bind to local address using automatic port
socket.Connect(new IPEndPoint(svrAddress, svrPort)); // Works fine without Bind, timeout with Bind
I've tried the same using the corresponding IPv6 addresses but I get the exact same result.
If I Bind the client on the same address (using a different port than the server), it works fine.
Any idea what I'm doing wrong?
EDIT Here is my test projects (it might be useful to someone)
Server part:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Server
{
class Program
{
static void Main(string[] args)
{
IPAddress[] ips = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
string line = string.Empty;
while (line != "q")
{
// Gets the IP address to listen on.
Console.WriteLine("IP to listen on:");
int count = 0;
foreach (IPAddress ip in ips)
Console.WriteLine("{0}: {1}", ++count, ip.ToString());
string numString = Console.ReadLine();
int pos = Convert.ToInt32(numString) - 1;
IPAddress myAddress = ips[pos]; // Removing or not the scope ID doesn't change anything as "localEndPoint" below will contain it no matter what
// Binds and starts listening.
IPEndPoint myEP = new IPEndPoint(myAddress, 12345);
Socket listeningSocket = new Socket(myAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listeningSocket.Bind(myEP);
listeningSocket.Listen(50);
IPEndPoint localEndPoint = (IPEndPoint)listeningSocket.LocalEndPoint;
Console.WriteLine("Listening on {0}:{1}", localEndPoint.Address, localEndPoint.Port);
Task.Factory.StartNew(() =>
{
try
{
// Accepts new connections and sends some dummy byte array, then closes the socket.
Socket acceptedSocket = listeningSocket.Accept();
IPEndPoint remoteEndPoint = (IPEndPoint)acceptedSocket.RemoteEndPoint;
Console.WriteLine("Accepted connection from {0}:{1}.", remoteEndPoint.Address, remoteEndPoint.Port);
acceptedSocket.Send(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
acceptedSocket.Close(5000);
Console.WriteLine("-= FINISHED =- Type q to quit, anything else to continue");
}
catch (Exception ex)
{ }
});
line = Console.ReadLine();
// Closes the listening socket.
listeningSocket.Close();
}
}
}
}
Client part
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Client
{
class Program
{
static void Main(string[] args)
{
IPAddress[] ips = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
string line = string.Empty;
while (line != "q")
{
// Gets the IP address to connect to (removes the "scope ID" if it's an IPv6).
Console.WriteLine("IP to connect to:");
int count = 0;
foreach (IPAddress ip in ips)
Console.WriteLine("{0}: {1}", ++count, ip.ToString());
string numString = Console.ReadLine();
int pos = Convert.ToInt32(numString) - 1;
IPAddress svrAddress = ips[pos].AddressFamily == AddressFamily.InterNetworkV6
? new IPAddress(ips[pos].GetAddressBytes())
: ips[pos];
Console.WriteLine("Connecting to " + svrAddress);
// Gets the IP address to bind on (can chose "none" - also removes the "scope ID" if it's an IPv6).
Console.WriteLine("IP to bind to:");
Console.WriteLine("0: none");
count = 0;
IPAddress[] filteredIps = ips.Where(i => i.AddressFamily == svrAddress.AddressFamily).ToArray();
foreach (IPAddress ip in filteredIps)
Console.WriteLine("{0}: {1}", ++count, ip.ToString());
numString = Console.ReadLine();
pos = Convert.ToInt32(numString) - 1;
IPEndPoint localEndPoint = (pos == -1)
? null
: new IPEndPoint(
filteredIps[pos].AddressFamily == AddressFamily.InterNetworkV6
? new IPAddress(filteredIps[pos].GetAddressBytes())
: filteredIps[pos]
, 0);
Console.WriteLine("Binding to " + (localEndPoint == null ? "none" : localEndPoint.Address.ToString()));
// Binds to an address if we chose to.
Socket socket = new Socket(svrAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (localEndPoint != null)
socket.Bind(localEndPoint);
Task.Factory.StartNew(() =>
{
try
{
// Connects to the server and receives the dummy byte array, then closes the socket.
socket.Connect(new IPEndPoint(svrAddress, 12345));
IPEndPoint remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
Console.WriteLine("Connected to {0}:{1}", remoteEndPoint.Address, remoteEndPoint.Port);
byte[] buffer = new byte[10];
Console.WriteLine((socket.Receive(buffer) == buffer.Length) ? "Received message" : "Incorrect message");
socket.Close();
}
catch (Exception ex)
{
// An exception occured: should be a SocketException due to a timeout if we chose to bind to an address.
Console.WriteLine("ERROR: " + ex.ToString());
}
Console.WriteLine("-= FINISHED =- Type q to quit, anything else to continue");
});
line = Console.ReadLine();
}
}
}
}
Actually it was a configuration issue with my network adapters and it has to do with "Weak and Strong Host model".
From what I've read ( Using a specific network interface for a socket in windows ) binding on Windows previous to Vista would only work for incoming traffic, and it wouldn't do anything for outgoing traffic.
Starting with Vista it's possible but by default it won't work: you need to allow the "weak host model" using
netsh interface ipv4 set interface "loopback" weakhostreceive=enabled
netsh interface ipv4 set interface "loopback" weakhostsend=enabled
See https://web.archive.org/web/20150402200610/http://blog.loadbalancer.org/direct-server-return-on-windows-2008-using-loopback-adpter/ for more info.
EDIT
Actually, instead of creating several loopback adapters and changing their host model, it's a lot better and easier to just create one loopback adapter, give it several IP addresses on a different network than your real IP, and then only use those IPs for your test. That way there's no routing issue, and you're sure everything stays local (as there's no routing between the real and loopback adapter).
Use below code in the server for binding the connection on all the interface on the same port.
// Binds and starts listening.
IPEndPoint myEP = new IPEndPoint(IPAddress.Any, 12345);

Categories