Turning a IP Address into a valid URI - c#

I have been trying to navigate my webview element in my windows store app to '192.168.0.1' but for some reason the Uri class can not parse it, is there a way to make convert a IP Address into a Uri?

You can also use UriBuilder and not have to manually add the "http://".
var builder = new UriBuilder("192.168.0.1");
var uri = builder.Uri;

The answer to this is to add the prefix of the ip's protocol:
http:// or https://, for instance
new Uri("192.168.0.1") would have to be new Uri("http://192.168.0.1/")
Thanks to Bob Kaufman

Related

strip off prefix of URL's

I have got the following log of URL strings. The logs contain millions of records.
www.example.com/p1?q=k
example.com/p1?q=k
http://example.com/p1?q=k
https://example.com/p1?q=k
http://www.example.com/p1?q=k
I used the C# Uri class but it throws an excepition for format of type "example.com/p1?q=K"
I was wondering if there is a generally/standard accepted method for dealing with such different types of URL to get websitename & the relative URL.
P.S: I could strip off http:// & https:// by using a regex or string comparision, but curious to know if there are any elegant solutions
If you try it with your existing example it will not work.. however you can play around with this and do some appending code where needed which means you will need to create a few variables to store the http://, https://, and www.
System.Uri uriPre = new Uri ("http://www.example.com/p1?q=k");
string uriString = uriPre.Host + uriPre.PathAndQuery;
uriString = uriString.Replace("www.", "");
yields
"example.com/p1?q=k"
the rest of the coding you will have to figure out because only you would know when to utilize the different protocols base on the example I've provided
to expand on Alexei Levenkov answer here is an example that you can use to try to create a new Uri.
Uri tempValue;
var uriPre = new Uri(string.Empty, UriKind.Relative);
if (Uri.TryCreate("example.com/p1?q=k", UriKind.Relative, out tempValue))
{
// do something or retrun tempValue;
}
Uri it the class that is designed to deal with Uris
var noSchemaRelativeUri = new Uri("example.com/foo", UriKind.Relative);
Either UriBuilder or Uri(Uri base, Uri relative) can be used to construct absolute Uri.
To pick between relative and aboslute you can use Uri.TryCreate.
Note. "www.example.com" and "example.com" strictly speaking are unrelated domain names, converting one to another is not guaranteed to always produce registered domain name (also indeed most sites register both and do some sort of redirect between).

Url works when pinging but causes UriFormatException

I have a mail server I'm trying to connect to with exchange web services. If I ping the server, it works, but it gets a UriFormatException when provided in code.
Urls that work in command prompt but fail in c#
myserver.mydomain.com
myserver
192.168.100.1 (my server's ip)
Urls that can be parsed into URIs but fail to be pinged
http://myserver.mydomain.com
http://192.168.100.1
I also tried adding \\ to the beginning but had no luck.
We do have a bit of a weird setup with connecting to our domain when on-network that I believe is what is causing http://myserver.mydomain.com to fail in ping. How can I turn the base url (without the http://) into a string that will be valid for a c# Uri?
Code:
var serverUrl = "myserver.mydomain.com"; //base string I'd like to use
_exchange.Url = new Uri(serverUrl); //causes UriFormatException: Invalid URI: The format of the URI could not be determined.
To consturct Uri from host name use UriBuilder:
var builder = new UriBuilder();
builder.Host = "myserver.mydomain.com";
var uri = builder.Uri;
Note that what you call "uri" (myserver.mydomain.com) is actually "host name" or "DNS name" which is what get resolved to IP and than used to Ping. "http://myserver.mydomain.com" is absolute Uri for particular protocol (HTTP).

How to get website name from domain name?

I fetch the domain from the URL as follows:
var uri = new Uri("Http://www.google.com");
var host = uri.Host;
//host ="www.google.com"
But I want only google.com in Host,
host = "google.com"
Given the accepted answer I guess the issue was not knowing how to manipulate strings rather than how to deal with uris... but for anyone else who ends up here:
The Uri class does not have this property so you will have to parse it yourself.
Presumably you do not know what the subdomain is before time so a simple replace may not be possible.
This is not trivial since the TLDs are so varied (http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains), and there maybe be multiple parts to the url (eg http://pre.subdomain.domain.co.uk).
You will have to decide exactly what you want to get and how complex you want the solution to be.
simple - do a string replace, see ekad's answer
medium - regex that works most of the time, see Strip protocol and subdomain from a URL
or complex - refer to a list of suffixes in order to figure out what is subdomain and what is domain eg
Get the subdomain from a URL
If host begins with "www.", you can replace "www." with an empty string using String.Replace Method like this:
var uri = new Uri("Http://www.google.com");
var host = uri.Host.ToLower();
if (host.StartsWith("www."))
{
host = host.Replace("www.", "");
}

How do I force a relative URI to use https?

I have a relative URI:
Uri U = new Uri("../Services/Authenticated/VariationsService.svc",
UriKind.Relative);
The problem is that depending on whether the user has typed https:// or http:// into their web browser to get to the silverlight application, it may use either http or https when trying to contact the service.
I want to force the program to use https for connecting to the service eitherway.
Initially I tried this:
Uri U = new Uri("../Services/Authenticated/VariationsService.svc",
UriKind.Relative);
string NU = U.AbsoluteUri;
U = new Uri(NU.Replace("http://", "https://"), UriKind.Absolute);
But it fails at U.AbsoluteUri because it can't convert the relative Uri into an absolute Uri at that stage. So how do I change the Uri Scheme to https?
The relative path has to be converted to absolute first. I do that using the Uri of the excuting Silverlight XAP file.
There might be ways to reduce this a bit (it feels wrong doing string operations with Uris) but it's a start:
// Get the executing XAP Uri
var appUri = App.Current.Host.Source;
// Remove the XAP filename
var appPath = appUri.AbsolutePath.Substring(0, appUri.AbsolutePath.LastIndexOf('/'));
// Construct the required absolute path
var rootPath = string.Format("https://{0}{1}", appUri.DnsSafeHost, appUri.AbsolutePath);
// Make the relative target Uri absolute (relative to the target Uri)
var uri = new Uri(new Uri(rootPath), "../Services/Authenticated/VariationsService.svc");
This does not include transferring a portnumber (which you might want to do in other circumstance). Personally I would put the above code in a helper method that also handles the port (and whatever you want to do differently when running localhost).
Hope this helps.
Instead, you should change your ASPX file which hosts your silverlight, and force user to redirect to SSL only if he/she is logged in using non SSL url. Because ideally it would be perfect if silverlight opens connection only to the same domain and scheme it loaded from.
The protocol is a separate component, so I think that you can just put it in front of your relative address:
Uri U = new Uri("https:../Services/Authenticated/VariationsService.svc", UriKind.Relative);
"Scheme" does not have any meaning in a relative URI. You'll have to convert it to an absolute URI at some point to change the scheme.

C#: Get IP Address from Domain Name?

How can I get an IP address, given a domain name?
For example: www.test.com
You can use the System.Net.Dns class:
Dns.GetHostAddresses("www.test.com");
You could use the GetHostAddresses method:
var address = Dns.GetHostAddresses("www.test.com")[0];
You can get the same results by using:
Dns.GetHostAddresses("yahoo.com");
or
await Dns.GetHostAddressesAsync("yahoo.com");
My answer could be more the same above answers, but here i get the current web app hosted URL / domain name using code and obtained the IP address and from that. I used the code in my C# MVC Web app and its working fine.
Uri myUri = new Uri(((System.Web.HttpContextWrapper)HttpContext).Request.Url.ToString());
var ipAddress = Dns.GetHostAddresses(myUri.Host).FirstOrDefault().ToString();

Categories