#include "stdafx.h"
#include <WinSock2.h>
#include <iostream>
#include <string>
#include <map>
using namespace std;
#pragma comment(lib,"ws2_32")
bool isPortOpen(const char* szIp,int nPort)
{
SOCKET sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (sock == INVALID_SOCKET)
return false;
SOCKADDR_IN addr;
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(szIp);
addr.sin_port = htons(nPort);
int nRet = connect(sock,(sockaddr*)&addr,sizeof(addr));
closesocket(sock);
return (nRet==0)?true:false;
}
std::string getDirPath()
{
std::string strPath;
char szPath[MAX_PATH] = {0};
memset(szPath,0,MAX_PATH);
GetModuleFileName(NULL,szPath,MAX_PATH);
strPath = szPath;
size_t np1 = strPath.find_last_of('\\');
if (np1 != std::string::npos)
strPath = strPath.substr(0,np1+1);
return strPath;
}
#define app_name "app"
#define server_name "server"
#define port_name "port"
#define err_name "err"
std::multimap<std::string,int> g_sp;
void loadConfigIni()
{
std::string strOptFile = getDirPath() + "opt.ini";
char szValue[1024] = {0};
char szServer[1024] = {0};
char szPort[1024] = {0};
int nPort = 0;
int i=0;
for (;;)
{
_snprintf(szServer,1024,"%s%d",server_name,i);
_snprintf(szPort,1024,"%s%d",port_name,i++);
GetPrivateProfileString(app_name,szServer,err_name,szValue,1024,strOptFile.c_str());
if (stricmp(szValue,err_name) == 0)
break;
nPort = GetPrivateProfileInt(app_name,szPort,-1,strOptFile.c_str());
if (nPort == -1)
break;
g_sp.insert(std::make_pair(szValue,nPort));
}
}
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
memset(&wsaData,0,sizeof(WSADATA));
WSAStartup(MAKEWORD(2,2),&wsaData);
loadConfigIni();
std::multimap<std::string,int>::iterator it = g_sp.begin();
for (; it != g_sp.end(); it++)
{
if (isPortOpen((it->first).c_str(),it->second))
printf("[%s][%d] open.\n",(it->first).c_str(),it->second);
else
printf("[%s][%d] close.\n",(it->first).c_str(),it->second);
}
getchar();
WSACleanup();
return 0;
}