// 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;
}
参考
[技术专题] [原创]获取URL中主机域名的小技巧!
http://bbs.pediy.com/thread-179681.htm