不带子域的 NSURL 的主机

发布于 2024-10-16 19:16:28 字数 538 浏览 6 评论 0原文

如何获取没有子域的 NSURL 主机

以下是一些输入。
应该保留的部分用粗体显示,应该删除的部分用斜体显示:

server.com
www.server.com
媒体。server.com
host1.media.server.com

到目前为止,听起来很容易实现。
但它也应该正确处理以下输入,以及任何我没有想到的奇怪情况,这些情况在任何相关 RFC 中都被普遍接受或指定。

server.co.uk
媒体。server.co.uk
127.0.0.1
...

How can you get the host of an NSURL without the subdomains?

Here are some inputs.
The part that should remain is in bold, and what should be stripped is in italic:

server.com
www.server.com
media.server.com
host1.media.server.com

So far, sounds very easy to implement.
But it should also correctly handle the following inputs, as well as any weird case I didn't think about that is commonly accepted or specified in any relevant RFC.

server.co.uk
media.server.co.uk
127.0.0.1
...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柒夜笙歌凉 2024-10-23 19:16:28

请参阅从主机名中提取域名这个问题似乎不存在有一个简单的解决方案。

See Extract domain name from a host name This problem doesn't seem to have an easy solution.

一影成城 2024-10-23 19:16:28

这并没有回答这个难题,但是如果您将 URL 与特定域的白名单相匹配(就像我发现这个问题时一样),您可以使用如下代码来检查:

NSArray *domainsForVideo = @[@"youtube.com",
                             @"youtu.be",
                             @"videoschool.pvt.k12.md.us",
                             @"vimeo.com"];

NSString *host = [url host]; //where URL is some NSURL object

BOOL hostMatches = NO;

for (NSString *testHost in domainsForVideo) {
    if ([[host lowercaseString] isEqualToString:testHost]) hostMatches = YES;  // matches youtube.com exectly

    NSString *testSubdomain = [NSString stringWithFormat:@".%@",testHost];  // matches www.youtube.com but not fakeyoutube.com
    if ([[host lowercaseString] rangeOfString:testSubdomain].location != NSNotFound) hostMatches = YES;
}

if (hostMatches) {
    // this is a Video URL
}

This doesn't answer the hard question, but if you're matching a URL to a white list of specific domains (like I was when I found this question) you can use code like this to check:

NSArray *domainsForVideo = @[@"youtube.com",
                             @"youtu.be",
                             @"videoschool.pvt.k12.md.us",
                             @"vimeo.com"];

NSString *host = [url host]; //where URL is some NSURL object

BOOL hostMatches = NO;

for (NSString *testHost in domainsForVideo) {
    if ([[host lowercaseString] isEqualToString:testHost]) hostMatches = YES;  // matches youtube.com exectly

    NSString *testSubdomain = [NSString stringWithFormat:@".%@",testHost];  // matches www.youtube.com but not fakeyoutube.com
    if ([[host lowercaseString] rangeOfString:testSubdomain].location != NSNotFound) hostMatches = YES;
}

if (hostMatches) {
    // this is a Video URL
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文