How can service know the caller? - c#

I have a WCF service.
How can i know if the call to my service comes from local machine or a machine from network?
Thanks,
Adrya

You could check the IP of the caller. If it is from the local machine should be "127.0.0.1".
You can get the IP of the caller (the remote address) from the OperationContext object.
More info here:
http://www.danrigsby.com/blog/index.php/2008/05/21/get-the-clients-address-in-wcf/

I'd compile a list at startup of ALL the known IP addresses on the local machine using something like....
NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces();
List<string> addressList = new List<string>();
foreach (NetworkInterface ni in nis)
{
IPInterfaceProperties iip = ni.GetIPProperties();
UnicastIPAddressInformationCollection unis = iip.UnicastAddresses;
foreach (UnicastIPAddressInformation uni in unis)
{
string address = uni.Address.ToString();
addressList.Add(address);
}
}
and then check the addressList to see if it contains the 'remote' IP address.
That should cover any request presenting itself from the local machine with an IP addy other than 127.0.0.1.

Related

Get IP address from hostname in LAN

I found many samples on how to get a hostname by an IP address, how can I get the IP address of a host in the LAN?
Try this
public static void DoGetHostAddresses(string hostname)
{
IPAddress[] ips;
ips = Dns.GetHostAddresses(hostname);
Console.WriteLine("GetHostAddresses({0}) returns:", hostname);
foreach (IPAddress ip in ips)
{
Console.WriteLine(" {0}", ip);
}
}
i got this from http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses.aspx
Here is simple code if you want to get the IP Address(V4) from your pc.
Import this library into your class
using System.Net;
Initialize and declare these variables into your codes. They contain hostname, ipaddress and an array of Host Addresses:
string HostName = Dns.GetHostName().ToString();
IPAddress[] IpInHostAddress = Dns.GetHostAddresses(HostName);
string IPV4Address = IpInHostAddress[1].ToString(); //Default IPV4Address. This might be the ip address you need to retrieve
string IPV6Address = IpInHostAddress[0].ToString(); //Default Link local IPv6 Address
Open your command prompt, just type "ipconfig" and press enter.Once you are done, you could check if the string IPV4Address matches to IPv4Address in our pc.
As long as you know the name of a machine, you can use Dns.GetHostAddresses. Your network DNS should recognize it as LAN computer and return proper IP.
Use Dns.GetHostEntry(hostname) instead of obsolete Dns.GetHostAddresses.
Here is an excellent example of how it is doing: http://www.codeproject.com/Articles/854/How-To-Get-IP-Address-Of-A-Machine
you could use the windows management classes to do this, it also works for remote machines that are in the same domain (but I don't know if they need to enable or disable any security or policy settings for this to work). for example:
public List<NetworkAdapter> GetAdapterList()
{
ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapterConfiguration ");
ManagementObjectCollection moc = mgmt.GetInstances();
List<NetworkAdapter> adapters = new List<NetworkAdapter>();
// Search for adapters with IP addresses
foreach(ManagementObject mob in moc)
{
string[] addresses = (string[])mob.Properties["IPAddress"].Value;
if (null == addresses)
{
continue;
}
NetworkAdapter na = new NetworkAdapter();
na.Description = (string) mob.Properties["Description"].Value;
na.MacAddress = (string) mob.Properties["MACAddress"].Value;
na.IPAddresses = addresses;
adapters.Add(na);
}
return adapters;
}
and to access a remote machine create the management class like this instead:
ManagementClass mgmt = new ManagementClass
(\\\\servername\\root\\cimv2:Win32_NetworkAdapterConfiguration);
this approach may get you more IPs than just the ones that have been registered in the DNS.

How do you determine which adapter is used?

I have a need to figure out which adapter is used when a connection is created. In other words, if I have multiple NIC cards (i.e. wireless, lan, etc) on my machine, which card is being used for the connection?
If anyone can point me in the right direction...
In C#
foreach(var nic in NetworkInterface.GetAllNetworkInterfaces.Where(n => n.OperationalStatus == OperationStatus.UP)
{
if(nic.GetIsNetworkAvailable())
{
//nic is attached to some form of network
}
}
VB .NET
ForEach nic in NetworkInterface.GetAllNetworkInterfaces.Where(Function(n) n.OperationalStatus = OperationStatus.UP)
If nic.GetIsNetworkAvailable() Then
//nic is attached to some form of network
End If
Next
This will only test active working Network Interfaces that are connected to an active network.
Why don't you use the MAC address?
Maybe you could map it by the MAC Address:
var nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (var nic in nics)
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
var mac = nic.GetPhysicalAddress().ToString();
if (mac == "your:connections:mac:address")
{
/* ... */
}
}
}
The "your:connections:mac:address" part you can figure out following this method, using the IP address of the LocalEndPoint.
How do I obtain the physical (MAC) address of an IP address using C#?
It's not beautiful, but it could work.

Problem Converting ipv6 to ipv4

I have some code in an asp.net app that needsto get the ipv4 address of the client computer (the users are all on our own network). Recently we upgraded the server the app runs on to windows 2008 server. Now the Request.UserHostAddress code returns the ipv4 when the client is on an older OS and ipv6 when they are on a newer OS (Vista and higher). So the feature that relys on this works for some clients and not others.
I added code that is supposed to convert from ipv6 to ipv4 to try to fix this problem. It's from this online tutorial: https://web.archive.org/web/20211020102847/https://www.4guysfromrolla.com/articles/071807-1.aspx .I'm using dsn.GetHostAddress and then looping through the IPs returned looking for one that is "InterNetwork"
foreach (IPAddress IPA in Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != String.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
The problem is that this isn't working for me. The clients connecting from ipv4 continue to return the correct ipv4 IP of the client computer, but the clients connecting from Vista and Windows 7 it is returning the ipv4 IP of the SERVER machine not the client computer.
Simple answer: Disable IPV6 on the server, or remove the IPV6 address of the server from the DNS entry.
There is not a magic IPV4<->IPV6 converter. They're completely different protocols, and addresses in one don't translate to the other. If you want to reliably retrieve the IPV4 address of the client, you need to make sure that the client connects over IPV4.
I also had copied the example code and a colleague pointed out that it was obviously buggy.
This line uses the host name of the server, hence the incorrect result:
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
I have corrected the code in my project as follows:
/// <summary>
/// Returns the IPv4 address of the specified host name or IP address.
/// </summary>
/// <param name="sHostNameOrAddress">The host name or IP address to resolve.</param>
/// <returns>The first IPv4 address associated with the specified host name, or null.</returns>
public static string GetIPv4Address(string sHostNameOrAddress)
{
try
{
// Get the list of IP addresses for the specified host
IPAddress[] aIPHostAddresses = Dns.GetHostAddresses(sHostNameOrAddress);
// First try to find a real IPV4 address in the list
foreach (IPAddress ipHost in aIPHostAddresses)
if (ipHost.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
return ipHost.ToString();
// If that didn't work, try to lookup the IPV4 addresses for IPV6 addresses in the list
foreach (IPAddress ipHost in aIPHostAddresses)
if (ipHost.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
IPHostEntry ihe = Dns.GetHostEntry(ipHost);
foreach (IPAddress ipEntry in ihe.AddressList)
if (ipEntry.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
return ipEntry.ToString();
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex);
}
return null;
}
The code above works in ASP.Net 2.0 on Windows 7/Server 2008.
Hope this helps.
if you are using .Net 4.5 Framework then there is a method provide to convert IP6 to IP4
public IPAddress MapToIPv4()
You can find the details here

Get IP of my machine C# with virtual machine installed

I want to get the current IP address of the computer that has say 3 virtual machines (VM Ware) installed. I want to get LAN address of that computer.
current code that i have returns me an array but how to identify current computer lan address ?
public static string getThisCompIPAddress()
{
IPAddress[] addresslist = Dns.GetHostAddresses(Dns.GetHostName());
return (addresslist[0].ToString());
}
addresslist returns an array of 3 IP addresses
You could try the NetworkInterface class, and try to match the name or physical address of the LAN connection to find out the real one. Maybe searching within this class and it's members you can find something that suits your needs.
Here is a simple method to provide some usage info:
using System.Net.NetworkInformation;
...
static void ViewNetworkInfo()
{
NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nw in networks)
{
Console.WriteLine(nw.Name);
Console.WriteLine(nw.GetPhysicalAddress().ToString());
IPInterfaceProperties ipProps = nw.GetIPProperties();
foreach (UnicastIPAddressInformation ucip in ipProps.UnicastAddresses)
{
Console.WriteLine(ucip.Address.ToString());
}
Console.WriteLine();
}
Console.ReadKey();
}
I've tried all of the solutions above but couldn't get the ip from my "real" machine and not the virtual one. I've managed to use this to get the IP from my virtual machine:
IPAddress[] addresslist = Dns.GetHostAddresses(Environment.ExpandEnvironmentVariables("%CLIENTNAME%"));
The reason why I used it this way is that the function Dns.GetHostAddresses return the adresses of the given host, so if you use the Dns.GetHostName() function it will return the virtual-machine name and not the local machine, but using the name of the machine where you can find using the: Environment.ExpandEnvironmentVariables("%CLIENTNAME%") you can get the client name and not the virtual-machine name, this way you can get the real IP of your local machine.
I hope this helps.
public static ArrayList getThisCompIPAddress()
{
ArrayList strArrIpAdrs = new ArrayList();
ArrayList srtIPAdrsToReturn = new ArrayList();
addresslist = Dns.GetHostAddresses(Dns.GetHostName());
for (int i = 0; i < addresslist.Length; i++)
{
try
{
long ip = addresslist[i].Address;
strArrIpAdrs.Add(addresslist[i]);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
foreach (IPAddress ipad in strArrIpAdrs)
{
lastIndexOfDot = ipad.ToString().LastIndexOf('.');
substring = ipad.ToString().Substring(0, ++lastIndexOfDot);
if (!(srtIPAdrsToReturn.Contains(substring)) && !(substring.Equals("")))
{
srtIPAdrsToReturn.Add(substring);
}
}
return srtIPAdrsToReturn;
}
this is 100% working, the real problem was that it was throwing error while calculating Address that returns long. Error Code is 10045

How do I get the Local Network IP address of a computer programmatically?

I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.
How can I accomplish this?
If you are looking for the sort of information that the command line utility, ipconfig, can provide, you should probably be using the System.Net.NetworkInformation namespace.
This sample code will enumerate all of the network interfaces and dump the addresses known for each adapter.
using System;
using System.Net;
using System.Net.NetworkInformation;
class Program
{
static void Main(string[] args)
{
foreach ( NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces() )
{
Console.WriteLine("Network Interface: {0}", netif.Name);
IPInterfaceProperties properties = netif.GetIPProperties();
foreach ( IPAddress dns in properties.DnsAddresses )
Console.WriteLine("\tDNS: {0}", dns);
foreach ( IPAddressInformation anycast in properties.AnycastAddresses )
Console.WriteLine("\tAnyCast: {0}", anycast.Address);
foreach ( IPAddressInformation multicast in properties.MulticastAddresses )
Console.WriteLine("\tMultiCast: {0}", multicast.Address);
foreach ( IPAddressInformation unicast in properties.UnicastAddresses )
Console.WriteLine("\tUniCast: {0}", unicast.Address);
}
}
}
You are probably most interested in the UnicastAddresses.
Using Dns requires that your computer be registered with the local DNS server, which is not necessarily true if you're on a intranet, and even less likely if you're at home with an ISP. It also requires a network roundtrip -- all to find out info about your own computer.
The proper way:
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface adapter in nics)
{
foreach(var x in adapter.GetIPProperties().UnicastAddresses)
{
if (x.Address.AddressFamily == AddressFamily.InterNetwork && x.IsDnsEligible)
{
Console.WriteLine(" IPAddress ........ : {0:x}", x.Address.ToString());
}
}
}
(UPDATE 31-Jul-2015: Fixed some problems with the code)
Or for those who like just a line of Linq:
NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(adapter=> adapter.GetIPProperties().UnicastAddresses)
.Where(adr=>adr.Address.AddressFamily == AddressFamily.InterNetwork && adr.IsDnsEligible)
.Select (adr => adr.Address.ToString());
In How to get IP addresses in .NET with a host name by John Spano, it says to add the System.Net namespace, and use the following code:
//To get the local IP address
string sHostName = Dns.GetHostName ();
IPHostEntry ipE = Dns.GetHostByName (sHostName);
IPAddress [] IpA = ipE.AddressList;
for (int i = 0; i < IpA.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ());
}
As a machine can have multiple ip addresses, the correct way to figure out your ip address that you're going to be using to route to the general internet is to open a socket to a host on the internet, then inspect the socket connection to see what the local address that is being used in that connection is.
By inspecting the socket connection, you will be able to take into account weird routing tables, multiple ip addresses and whacky hostnames. The trick with the hostname above can work, but I wouldn't consider it entirely reliable.
If you know there are one or more IPv4 addresses for your computer, this will provide one of them:
Dns.GetHostAddresses(Dns.GetHostName())
.First(a => a.AddressFamily == AddressFamily.InterNetwork).ToString()
GetHostAddresses normally blocks the calling thread while it queries the DNS server, and throws a SocketException if the query fails. I don't know whether it skips the network call when looking up your own host name.

Categories

Resources