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
Related
I'm trying to add a new header to a request I already had (which worked before), in which I want to put some sort of User-Agent string formatted like this:
AppName/AppVersion (DeviceOS DeviceOSVersion)
The code for it is written like this (request is a HttpRequestMessage):
request.Headers.Add(UserAgentKey, $"{AppName}/{DependencyService.Get<IVersionProperties>().GetAppVersion()} ({Device.RuntimePlatform} {DependencyService.Get<IVersionProperties>().GetOSVersion()})");
But weirdly enough it splits the string in two parts on the withspace (between the appverion and the opening parenthesis) resulting in 2 values for the User-Agent header instead of 1 unified whole.
So I'm curious what I'm doing wrong here, I think it has something to do with the whitespace and I might need to escape it somehow, but I'm not sure how. I hope someone can help me with this issue.
Thanks in advance.
Maybe not a full-on solution, but at least a workaround, why not compose the string first: var userAgent = $"{AppName}/{DependencyService.Get<IVersionProperties>().GetAppVersion()} ({Device.RuntimePlatform} {DependencyService.Get<IVersionProperties>().GetOSVersion()});"
And then take out the newlines: userAgent = userAgent.Replace(Environment.NewLine, " ");
As for the cause, I would say that one of these values has a newline in it. Although I don't really see why or which. Did you inspect each of the values individually?
Apparently it had to do with the header I was using.
I used the header "User-Agent" which expects a certain format and has some other funny business attached to it, when I changed it to "User-Agentt" for example it worked just fine and since I don't explicity need the header to be called that I will just change the name of the header.
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("."));
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'm trying to extract the domain name from a string in C#. You don't necessarily have to use a RegEx but we should be able to extract yourdomain.com from all of the following:
yourdomain.com
www.yourdomain.com
http://www.yourdomain.com
http://www.yourdomain.com/
store.yourdomain.com
http://store.yourdomain.com
whatever.youdomain.com
*.yourdomain.com
Also, any TLD is acceptable, so replace all the above with .net, .org, 'co'uk, etc.
If no scheme present (no colon in string), prepend "http://" to make it a valid URL.
Pass string to Uri constructor.
Access the Uri's Host property.
Now you have the hostname. What exactly you consider the ‘domain name’ of a given hostname is a debatable point. I'm guessing you don't simply mean everything after the first dot.
It's not possible to distinguish hostnames like ‘whatever.youdomain.com’ from domains-in-an-SLD like ‘warwick.ac.uk’ from just the strings. Indeed, there is even a bit of grey area about what is and isn't a public SLD, given the efforts of some registrars to carve out their own niches.
A common approach is to maintain a big list of SLDs and other suffixes used by unrelated entities. This is what web browsers do to stop unwanted public cookie sharing. Once you've found a public suffix, you could add the one nearest prefix in the host name split by dots to get the highest-level entity responsible for the given hostname, if that's what you want. Suffix lists are hell to maintain, but you can piggy-back on someone else's efforts.
Alternatively, if your app has the time and network connection to do it, it could start sniffing for information on the hostname. eg. it could do a whois query for the hostname, and keep looking at each parent until it got a result and that would be the domain name of the lowest-level entity responsible for the given hostname.
Or, if all that's too much work, you could try just chopping off any leading ‘www.’ present!
I would recommend trying this yourself. Using regulator and a regex cheat sheet.
http://sourceforge.net/projects/regulator/
http://regexlib.com/CheatSheet.aspx
Also find some good info on Regular Expressions at coding horror.
Have a look at this other answer. It was for PHP but you'll easily get the regex out of the 4-5 lines of PHP and you can benefit from the discussion that followed (see Alnitak's answer).
A regex doesn't really fit your requirement of "any TLD", since the format and number of TLDs is quite large and continually in flux. If you limited your scope to:
(?<domain>[^\.]+\.([A-Z]+$|co\.[A-Z]$))
You would catch .anything and .co.anything, which I imagine covers most realistic cases...
I'm using IPAddress.TryParse() to parse IP addresses. However, it's a little too permissive (parsing "1" returns 0.0.0.1). I'd like to limit the input to dotted octet notation. What's the best way to do this?
(Note: I'm using .NET 2.0)
Edit
Let me clarify:
I'm writing an app that will scan a range of IPs looking for certain devices (basically a port scanner). When the user enters "192.168.0.1" for the starting address, I want to automatically fill in "192.168.0.255" as the ending address. The problem is that when they type "1", it parses as "0.0.0.1" and the ending address fills in as "0.0.0.255" - which looks goofy.
If you are interested in parsing the format, then I'd use a regular expression. Here's a good one (source):
bool IsDottedDecimalIP(string possibleIP)
{
Regex R = New Regex(#"\b(?:\d{1,3}\.){3}\d{1,3}\b");
return R.IsMatch(possibleIP) && Net.IPAddress.TryParse(possibleIP, null);
}
That regex doesn't catch invalid IPs but does enforce your pattern. The TryParse checks their validity.
An IP address is actually a 32 bit number - it is not xxx.xxx.xxx.xxx - that's just a human readable format for the same. So IP address 1 is actually 0.0.0.1.
EDIT: Given the clarification, you could either go with a regex as has been suggested, or you could format the short cuts to your liking, so if you want "1" to appears as "1.0.0.0". you could append that and still use the parse method.