I need to implement a method which extracts a hostname from FQDN. For example if a hypothetical mail server is mymail.somecollege.edu I want to get as a result mymail
And if I get illegal string (not real FQDN) need no get null or some error code
How can I extract hostname?-
I don`t want to make a parsing of the input by myself.But rather looking for existing API.
Thanks
I tried to search for the first dot '.' - substring before it is a hostname.
But I am looking for existing API
I could not find any helper/API class to obtain the hostname (mymail) from the FQDN (mymail.somecollege.edu). You may have to just parse it like you mentioned: Extract everything up to the first "." character. NOTE: hostnames are not allowed to contain "." character.
var fullyQualifiedDomainName = Dns.GetHostEntry("computer").HostName;
var hostName = fileComputerName.Substring(0, fullyQualifiedDomainName
.IndexOf("."));
Related
I have been searching for an solution and haven't been able to find one for this situation.
How can I compare two text files so that it only displays match?
ipaddress.txt contains:
10.30.16.221
10.30.16.228
10.30.16.223
I have another text file that displays the dns name along with ip address.
dns.txt contains:
dogs.com 10.30.16.221
cats.com 10.30.16.222
snakes.com 10.30.16.223
How can I compare ipaddress.txt and dns.txt so that it only return lines that contains a matching ip address?
It should return
dogs.com 10.30.16.221
snakes.com 10.30.16.223
Read all the lines of ipaddress.txt to a hashset:
var ips = File.ReadAllLines("ipaddress.txt").ToHashSet();
Then, for every line in DNS, ask the hashset whether it contaisn the IP from that line:
var matches = File.ReadAllLines("dns.txt").Where(line => hs.Contains(line.Split().Last()));
It's more efficient to do an exact query after extracting just the IP, than it is to e.g. put the IPs in a list and for each line of DNS ask "does this DNS line end with any of the IPs in the list". You could also look at something like line[line.LastIndexOf(' ')+1..] to extract the IP. Note that both of these assume that dns is nicely formed with no trailing spaces etc; if the data in it is a bit wonky you'll need to clean it up. You could also use something like:
var ips = File.ReadAllLines("ipaddress.txt");
var matches = File.ReadAllLines("dns.txt").Where(line => ips.Any(ip => line.Contains(ip)));
but it's potentially a lot more inefficient for large lists
How to check what is wrong in domain URL in C#
I want to updated domain URL when invalid domain enter.
Input Put of Domain: OutPut Like
1)http:/localhost:1234/------>http://localhost:1234/
2)http://localhost:1234------>http://localhost:1234/
3)http:localhost:1234/------->http://localhost:1234/
4)http:localhost:1234-------->http://localhost:1234/
5)localhost:1234/------------>http://localhost:1234/
6)localhost:1234------------->http://localhost:1234/
Also above all test cases with HTTPS
May be need add more test cases.
I have code of nopCommerece for warning but it's use only current store .
How I develop a code for enter domain is valid or not and return valid domain.
My understanding of the question is you want to take in a given URL and output a correction. At the very minumum you are looking for the string "localhost:1234". You could use a regular expression to check for the existence of this string. If true, output "http://localhost:1234/"
The regular express is "/localhost:1234/g" and can be found here: http://regexr.com/3e2n8
To check this regular expression in C# you will code:
Regex regex = new Regex(#"/localhost:1234/g");
Match match = regex.Match("http:/localhost:1234/"); // your given string
if (match.Success)
{
// your given string contains localhost:1234
}
In any domain name the following are important:
www..com:
portnumber is 80 by default
but still, to check and get the Exception, use this URL,
Best way to determine if a domain name would be a valid in a "hosts" file?
I'm trying to get all urls in one regular expression, currently i'm using this pattern.
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
However that regex returns the pages/files, instead of hosts. So instead of having to run a second regular expression, I'm hoping someone here can help
This returns http://www.yoursite.com/index.html
I'm attempting to return yoursite.com.
Also the the regex will be parsing from html and hosts will be checked after, so 100% accuracy isn't crucial.
Assuming that your regex:
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
Actually does parse the Urls (I haven't checked it), you could easily use a capture group to get the host:
/^(https?:\/\/)?(?<host>([\da-z\.-]+)\.([a-z\.]{2,6}))([\/\w \.-]*)*\/?$/
When you get the Match result, you can examine Groups["host"] to get the host name.
But you're much better off, in my opinion, just using Uri.TryCreate, although you'll need a little logic to get around the possible lack of a scheme. That is:
if (!Regex.IsMatch(line, "https?:\/\/"))
line = "http://" + line;
Uri uri;
if (Uri.TryCreate(line, UriKind.Absolute, out uri))
{
// it's a valid url.
host = uri.Host;
}
Parsing Urls is a pretty tricky business. For example, no individual dotted segment can exceed 63 characters, and there's nothing preventing the last dotted segment from having numbers or hyphens. Nor is it limited to 6 characters. You're better off passing the entire string to Uri.TryCreate than you are trying to duplicate the craziness of URL parsing with a single regular expression.
It's possible that the rest of the Url (after the host name) could be trash. If you want to eliminate that bit causing a problem, then extract everything up to the end of the host name:
^https?:\/\/[^\/]*
Then run that through Uri.TryCreate.
To capture just the yoursite.com from sample text http://www.yoursite.com/index?querystring=value you could use this expression, however this does not validate the string:
^(https?:\/\/)?(?:[^.\/?]*[.])?([^.\/?]*[.][^.\/?]*)
Live demo: http://www.rubular.com/r/UNR7qiQ0Eq
This question already has answers here:
How to check whether a string is a valid HTTP URL?
(11 answers)
Closed 8 years ago.
I am trying to filter out invalid url from valid ones using .NET.
I am using Uri.TryCreate() method for this.
It has the following syntax
public static bool TryCreate(Uri baseUri,string relativeUri,out Uri result)
Now I am doing this....
Uri uri = null;
var domainList = new List<string>();
domainList.Add("asas");
domainList.Add("www.stackoverflow.com");
domainList.Add("www.codera.org");
domainList.Add("www.joker.testtest");
domainList.Add("about.me");
domainList.Add("www.ma.tt");
var correctList = new List<string>();
foreach (var item in domainList)
{
if(Uri.TryCreate(item, UriKind.RelativeOrAbsolute, out uri))
{
correctList.Add(item);
}
}
I am trying the above code I expect it to remove asas and www.joker.testtest from the list, but it doesnt.
Can some one help me out on this.
Update :
just tried out with Uri.IsWellFormedUriString this too did'nt help.
More Update
List of Valid uri
http://www.ggogle.com
www.abc.com
www.aa.org
www.aas.co
www.hhh.net
www.ma.tt
List of invalid uri
asas
as##SAd
this.not.valid
www.asa.toptoptop
You seem to be confused about what exactly URL (or URI, the difference is not significant here) is. For example, http://stackoverflow.com is a valid absolute URL. On the other hand, stackoverflow.com is technically a valid relative URL, but it would refer to the file named stackoverflow.com in the current directory, not the website with that name. But stackoverflow.com is a registered domain name.
If you want to check whether a domain name is valid, you need to define what exactly do you mean by “valid”:
Is it a valid domain name? Check whether the string consists of parts separated by dots, each part can contain letters, numbers and a hyphen (-). For example, asas and this.not.valid are both valid domain names.
Could it be an Internet domain name? Domain names on the Internet (as opposed to intranet) are specific in that they always have a TLD (top-level domain). So, asas certainly isn't an Internet domain name, but this.not.valid could be.
Is it a domain name under existing TLD? You can download the list of all TLDs and check against that. For example, this.not.valid wouldn't be considered valid under this rule, but thisisnotvalid.com would.
Is it a registered domain name?
Does the domain name resolve to an IP address? A domain name could be registered, but it still may not have an IP address in its DNS record.
Does the computer the domain name points to respond to requests? The requests that make the most sense are a simple HTTP request (e.g. trying to access http://domaininquestion/) or ping.
Try this one:
public static bool IsWellFormedUriString(
string uriString,
UriKind uriKind
)
Or Alternativly you can do this using RegExp like :
^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$
Take alook at this list
The problem is that none of the urls you have added here will classify as Absolute URLs. For that you have to prefix the protocol of the URL to it.
You can test and find out that
www.stackoverflow.com - Relative URL
http://www.stackoverflow.com - Absolute URL
//www.stackoverflow.com - Absolute URL ( No surprise here. Refer RFC 3986: "Uniform Resource Identifier (URI): Generic Syntax", Section 4.2 )
The point is that you have to prefix at least // to show that its an absolute URL.
So, in a nutshell, since all your URLs are relative URLs, it passes all your tests.
All your examples are valid,
some are absolute URLs some are relative, thats why none are getting removed.
Else for each Uri, you might try and construct a HttpWebRequest class
and then check for correct responses.
After checking other's answer I am aware that you are not looking for existence of domain and ping back you need to test them based on your GRAMMER... or Syntax of domain name right?
For that you need to rely on regex test only... and make proper rule to eveluate the domain name and if they fail exclude them from the list.
You can adopt these patterns and modify one to suite your need and then test them with every element in the list.
all of your URIs are Well-Formatted URIs so TryCreate and IsWellFormedUriString will not work in your case.
from here, the solutions is trying to open the URI:
using(var client = new MyClient()) {
client.HeadOnly = true;
// fine, no content downloaded
string s1 = client.DownloadString("www.stackoverflow.com");
// throws 404
string s2 = client.DownloadString("www.joker.testtest");
}
I want to read the value of the X-Forwarded-For header value in a request.
I've tried
HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new char[] { ',' }).FirstOrDefault();
in C#.
OR do I need to split the header by ":" and the take the second string?
I am asking this because, Wikipedia says
The general format of the field is:
X-Forwarded-For: client1, proxy1, proxy2
The format that you get in return is client1, proxy1, proxy2
So you split it with the comma, and get the first to see the ip of your client.
If helps, this is a simple way of getting the user's IP address, considering the X_FORWARDED_FOR header
var forwardedFor = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
var userIpAddress = String.IsNullOrWhiteSpace(forwardedFor) ?
Request.ServerVariables["REMOTE_ADDR"] : forwardedFor.Split(',').Select(s => s.Trim()).FirstOrDefault();
Don't forget that X-Forwarded-For can contain whatever client writes there. It can contain XSS or SQL-injection inside.
Sometimes the first may contain one of the local (private) reserved addresses which is not useful. Also the first position(s) are open to to spoofing.
Update - April 2018: Sampling the cases of a live production website where the first address is local (private) indicates some configuration issue on the end user's network or his ISP. The cases are occurring only rarely (<1%) and consistently for the same end users.
The answer below suggests walking from right to left until you hit a public address. Not sure anyone actually does this but it points out the issue.
https://husobee.github.io/golang/ip-address/2015/12/17/remote-ip-go.html