Hostname with Special Caracteres - c#

In my WCF service, I need to publish it in the Bonjour service. The reason for this is to make the customers that consume my service know which computer it is running.
This works well.
But when I have machines with special characters in HostName, customers of this service can not eat because an error occurs in time to resolve the url.
Example: "http://máchine:8888/service.svc"
One solution would be to use thought to solve here the IP of the machine in place of the hostname. But when the computer works only with IPv6, I can not publish the service because the following error occurs: "Inalid URI: Invalid port specified."
How can I solve this problem without changing the HostName?

In my experience, when mapping zeroconf services to URLs, it's best to not rely on the service's host name. Resolve the service to an IP address (for example, with avahi, using avahi_service_resolver_new) and use the IP address in the URL. This avoids all sorts of problems with fancy hostnames and system resolvers that can't resolve zeroconf names (often the case on embedded systems).
If you got an error like "Inalid URI: Invalid port specified.", it sounds like you might simply have neglected to enclose the IP address in [square brackets]. The pseudocode for forming your URL should be:
if IP address contains ":"
url = "http://[" + ip address + "]:port/whatever"
else
url = "http://" + ip address + ":port/whatever"
There are two additional complications:
If you are using HTTPS, certificate matching will probably fail because the common name on the certificate won't match. It's not clear what to do about this in general because the very nature of an autodiscovered service usually means you can't meaningfully authenticate the server anyway. So you might be able to get away with just turning off certificate verification in your HTTP client.
You might not be able to use IPv6 link local address because there is a deficiency in the standard (RFC) for URL syntax that means it is not possible to attach a % character and an interface name to the address in the URL. Some HTTP clients allow the obvious extension to the standard to support scoped addresses, but others don't (for example, all of the major web browsers don't!).

Related

c# dns.GetHostEntry() not returning valid ip address

I inherited code that makes the call to Dns.GetHostEntry("10.1.12.180") (or by using the dns of the machine) and the IPHostEntry that is returned has a different ip address "10.100.160.18" If I run the code on the same subdomain (10.1.12) it works. Another developer using WireShark said he doesn't see the call being made and that I must be overriding the GetHostEntry call to return that specific address (we used to have that address on the network). I'm not overriding the call.
I know that I can circumvent the issue by using IPAddress.Parse() since I do have the correct ip address.
Any ideas why it would return the incorrect ip? It used to work. I have checked with IT and they don't have any mappings to the incorrect IP address. The only difference it that the machine with ip address 10.1.12.180 was updated to windows 10 (from Windows 7).
I have isolated the call so that I have a project that just makes the Dns.GetHostEntry() call.
IPHostEntry returns a list of addresses, not a single IP address. You should iterate IPHostEntry.AddressList to see all of them.
See here for example usage of Dns.GetHostEntry.
Also be aware Windows can override DNS lookups via the hosts file. This is, unfortunately, a common way to hijack DNS lookups on a specific machine.

Get external IP address of a website

I have seen many methods for easily retrieving the internal IP address of a machine or website. However, I can't seem to find a good way to retrieve the external IP address.
To clarify, if I provide a URL like bitbucket.org, I want to get the external IP address of bitbucket. Is there a web service out there that can easily do this?
EDIT: Suppose, for this case, that I am on the same network as bitbucket.org.
I am filling a database with information about all the websites our company manages. We want to keep track of the info and note periodic changes, with specific data. This program will be deployed on one of the local servers on the same network as the servers that the websites are running from. I believe the only good way of retrieving the external IP address for each site is to use an external web service.
You can use System.Net.Dns.GetHostEntry() to get IP address by the host name.
You could query an external public DNS server, e.g. Google's one at 8.8.8.8. From the command line
nslookup bitbucket.org 8.8.8.8
or in Linux dig bitbucket.org #8.8.8.8. There's a few C# libraries out there that will let you query a specific DNS server e.g. DnsNet built on top of this CodeProject article (found searching - I haven't tried it to recommend it). This does rely on Google continuing the service, though, but that seems safe.
You can use the ping utility. In windows, open up a command window by hitting the windows key + r and type
ping bitbucket.org
I think you can just use Dns.GetHostAddresses to get the IP Address. From the MSDN Documentation:
The GetHostAddresses method queries a DNS server for the IP addresses associated with a host name.
UPDATE:
If you are looking for a web service, try looking at whoisxmpapi.com. As you can see from this sample, they do provide the name server IP Address in their XML output. You can then use something like this to get the IP address directly from the name server!
If you are trying to get your "wan" ip instead of your local IP you could try something like this.
You could also add code like this inside a webservice and add it to the PC bitbucket is on (if it is really on your network and you can have access to install webservices).
Public Shared ReadOnly Property IpAddress() As String
Get
If String.IsNullOrWhiteSpace(_ipAddress) Then
Try
Dim webClient As New WebClient
Dim result As String = webClient.DownloadString("http://checkip.dyndns.org")
Dim fields = result.Split(" ")
_ipAddress = fields.Last
_ipAddress = _ipAddress.Replace("</body></html>", "")
Catch ex As Exception
_ipAddress = "errorFindingIp"
End Try
End If
Return _ipAddress
End Get
End Property

ASP.NET Request.ServerVariables yields local IP address not remote IP

Got an asp.net web page in c#. One thing we would like to do is track hits to the site including their IP address. I implemented some code (thanks to SO) but the logged IP address always seem to be local, ie: 192.168.x.x. I have tried it from a variety of devices, even my phone and Version MiFi just to make sure its not something weird with the ISP but the log always list the same 2-3 different internal ip addresses (seems to change a little as the day goes on).
Here is my function that gets the IP (again thanks to postings here on SO):
protected IPAddress GetIp(HttpRequest request)
{
string ipString;
if (string.IsNullOrEmpty(request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
ipString = request.ServerVariables["REMOTE_ADDR"];
else
ipString = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
IPAddress result;
if (!IPAddress.TryParse(ipString, out result))
result = IPAddress.None;
return result;
}
public void logHit()
{
IPAddress ip = GetIp(Request);
string sIP = ip.ToString();
}
I tried this as well which yields the same result:
HttpContext.Current.Request.UserHostAddress;
When I do a call on the client side using something like the service on appspot, it works just fine:
<script type="application/javascript">
function getip(json) {
//txtIP is a input box on the form
document.getElementById("txtIP").value = json.ip;
}
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>
I suppose I could do a round-about way by hitting that appspot link and parse it out but that seems like a whole lot of trouble for something that should be simple.
Could it be the IIS on the server? Some kind of redirect going on? The ip addresses logged are NOT the servers. The problem is I dont have direct access to it so I have to talk to the guys that admin it and would like to give them some direction before they just start changing things.
Thanks
Ernie
If the HTTP_X_FORWARDED_FOR header is truly supported, then I think this would not be either forward or reverse proxy server causing this, but more likely Dynamic Network Address Translation or Dynamic Port Address Translation, which is happening below the application layer on the TCP/IP stack and thus would not affect an HTTP request header.
There are many ways to configure NAT, most of which would not cause these symptoms, but it is certainly possible to configure NAT in a way that would present this problem. Dynamic NAT or Dynamic PAT would be two such examples, and I would suggest this is what you ask your network administrators.
For more on Dynamic NAT/PAT, with good examples, you could review: http://www.cisco.com/en/US/docs/security/asa/asa82/configuration/guide/nat_dynamic.html
In a typical NAT scenario, the request packets reach the NAT device (firewall or router) as:
FROM - 5.5.5.5 (public address of the client)
TO - 6.6.6.6 (the public address of the server)
The "typical" NAT configuration would rewrite only the destination, as follows:
FROM - 5.5.5.5
TO - 192.168.6.6 (the private address of the server)
In this typical case, the server would still see REMOTE_ADDR as 5.5.5.5, as that is the source address on the incoming request. Then, the packets would be returned to 5.5.5.5, and the response would return to the client successfully.
Now, in the case of dynamic PAT, for example, the request would reach the NAT device as follows:
FROM - 5.5.5.5
TO - 6.6.6.6
Then, the NAT device would rewrite both source and destination packets, maintaining this "dynamic" mapping for only the lifetime of the request:
FROM - 192.168.1.1:12345 (the dynamic PAT address)
TO - 192.168.6.6 (the private address of the server)
Now, when the server sees this request, it appears to be from private address 192.168.1.1. In fact, with a strict PAT all requests will appear to be from this address. In your case, there are 2 or 3 of these addresses, probably because you may have enough traffic that you risk running out of ports if you use only a single dynamic PAT address.
So, your REMOTE_ADDR is 192.168.1.1, because that is actually the source address on the request packets. There is no HTTP_X_FORWARDED_FOR, because the Dynamic PAT is occurring at a lower TCP/IP layer (address and not application).
Finally, the response is sent back to 192.168.1.1:12345, which routs to the NAT device, which for the duration of the request/response (see the Cisco documentation above) maps it back to 5.5.5.5, and then drops the "dynamic" mapping.
Everything worked perfectly, the client gets the response back, except that you have no idea of the actual client address from the viewpoint of the server. And if it is dynamic NAT in play, I don't see how you could get this information from the server.
Fortunately, you did exactly the right thing to get the information in javascript on the client, so this likely solves your problem as well as it could be solved.
It depends on your network structure. Simply a firewall or load balancer can change the variables which you are checking.
if you are using a load balancer check this:
How to get visitor IP on load balancing machine using asp.net
if your sever is behind a firewall check this:
Find if request was forwarded from firewall to IIS

Converting IP address to host name via DNS.GetHostEntry

I am trying to get the hostname by passing in the ip address. I use the following code.
System.Net.Dns.GetHostEntry("192.168.x.x").HostName
For some host the above code is returning correctly the hostname, but for few other host it throws an exception 'No Such host found'.
Could any one tell me why is this happening for some hosts?
I used the above code in an asp.net mvc application.
Not all IP's are setup properly with a reverse DNS entry. These IP's are typically end consumers on lazy ISP's who don't provide PTR records for their clients. If there's no reverse entry, you can bet there's no forward entry either. As such, these hosts have no hostname at all, hence the exception. You'll need to catch this exception for these hosts and use something else such as their IP as an identifier.
I'm using Dns.GetHostByAddress, even though it complains about being depreciated. (VS2010 targeting 3.5)
Dns.GetHostEntry seems to throw an exception if a the target host is not reachable even if DNS knows the hostname. There doesn't seem to be any .NET way around this except for using depreciated methods. :\
(edit: though the above answer is also true - some machines just don't have hostnames. my answer is just if you know it should have a hostname but GetHostEntry doesn't work)

how to convert ip address to url with VB.NET OR C#

I want to convert ip address to url. But i can't figure it out how to.
It's not entirely clear what you want - an example would have been helpful - but something as simple as:
string url = "http://" + ipAddress;
would quite possibly be enough.
EDIT: Okay, it sounds like you're trying to find the name for an IP address. In some ways that's quite simple:
IPHostEntry entry = Dns.GetHostEntry("72.29.94.50");
Console.WriteLine(entry.HostName);
However, this doesn't print eggheadcafe.com. It prints something entirely different:
72.29.94.50.static.dimenoc.com
That's entirely correct in terms of a reverse DNS lookup (run "nslookup 72.29.94.50" to see the same result)... but it's not what you were looking for.
The problem is that I believe this eggheadcafe.com is served by virtual hosting - although eggheadcafe.com is served on that IP address, so are other websites (at least potentially). When you visit eggheadcafe.com in your browser, it resolves to that IP address but also specifies the host name in an HTTP header.
Not sure what you want to achieve but guess you need to resolve a host name from IP.
In this case you can use Dns.GetHostEntry method.
There are possibility of multiple website hosted on single IP. But you can get default using
IPHostEntry IpEntry = Dns.GetHostByAddress(ip);
return iphostentry.HostName.ToString();
Following might helpful to start with:
http://www.c-sharpcorner.com/UploadFile/uchukamen/IPAddHostConverter12052005041212AM/IPAddHostConverter.aspx

Categories

Resources