【C++】获取URL中主机域名

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <string>


typedef enum
{
    TYPE_NULL,  //XParseURL分析出错,或者地址错误
    TYPE_FTP,
    TYPE_HTTP,
    TYPE_HTTPS,
}URLTYPE;

URLTYPE XParseURL(LPCTSTR lpURL)
{
    int nPort = 0;

    TCHAR lpszHost[1024] = L"0";
    TCHAR lpszObject[1024] = L"0";
    URLTYPE urltype;
    int     nSize = 0;
    int     i;
    TCHAR   lpszURL[1024];
    LPCTSTR lpHttp = _T("http://");
    LPCTSTR lpHttps = _T("https://");
    LPCTSTR lpftp = _T("ftp://");

    lstrcpy(lpszURL, lpURL);

    for (i = 0; i < wcslen(lpszURL); i++)
    {
        if (_T('\\') == lpszURL[i]) lpszURL[i] = _T('/');
    }

    //判断协议
    if (CSTR_EQUAL == CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, lpHttp, lstrlen(lpHttp), lpURL, lstrlen(lpHttp)))
    {
        nSize = lstrlen(lpHttp);
        urltype = TYPE_HTTP;
    }
    else if (CSTR_EQUAL == CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, lpHttps, lstrlen(lpHttps), lpURL, lstrlen(lpHttps)))
    {
        nSize = lstrlen(lpHttps);
        urltype = TYPE_HTTPS;

    }
    else if (CSTR_EQUAL == CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, lpftp, lstrlen(lpftp), lpURL, lstrlen(lpftp)))
    {
        nSize = lstrlen(lpftp);
        urltype = TYPE_FTP;
    }
    else
    {
        urltype = TYPE_NULL;
        return urltype;
    }


    //找页面
    for (i = nSize; i < lstrlen(lpszURL); i++)
    {
        if (_T('/') == lpszURL[i])
        {
            //这里有点小问题
            //if (!lpszObject)
            //{ 
                lstrcpy((LPWSTR)lpszObject, &lpszURL[i + 1]);
            //};
            lpszURL[i] = 0;
            break;
        }
    }

    //找端口
    for (i = nSize; i < lstrlen(lpszURL); i++)
    {
        if (_T(':') == lpszURL[i])
        {
            if (!nPort) 
            {
                nPort = _ttoi(&lpszURL[i + 1]);
            };
            lpszURL[i] = 0;
            break;
        }
    }
    if (lpszHost)
    {
        lstrcpy(lpszHost, &lpszURL[nSize]);
    }

    printf("主机:%ls ,端口:%d ,页面:%ls \n", lpszHost, nPort, lpszObject);

    return urltype;
}

int main()
{
    int i = XParseURL(L"https://www.baidu.com:3389/test/admin.html");

    printf("协议 ");
    //协议判断
    switch (i)
    {
    case 0: printf("NULL \n"); break;
    case 1: printf("ftp \n");  break;
    case 2: printf("http \n");  break;
    case 3: printf("https\n");  break;

    default:

        break;
    }

    return 0;
}

549050-20170401155036992-219402049.png

参考

[技术专题] [原创]获取URL中主机域名的小技巧!
http://bbs.pediy.com/thread-179681.htm

转载于:https://www.cnblogs.com/17bdw/p/6656286.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值