Example #1
0
void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
    switch(id)
    {
        case IDC_OK:
		{
			if(InitSock())
			{
				SOCKET httpsock = socket(AF_INET , SOCK_STREAM , IPPROTO_TCP);
				if (INVALID_SOCKET == httpsock)  
				{  
					WSACleanup();
					return 0;
				 } 
				if(!ConnectServer(&httpsock,"",110))
				{
					MessageBox(user->hwnd,TEXT("·þÎñÆ÷Á¬½Óʧ°Ü£¡"),TEXT(""),MB_OK || MB_ICONWARNING);
					return 0;
				}
				ret = connectUserMail(httpsock,user->name,user->pass);
				if(ret)
				{
					
				}
			}
		}
        break;
        default:
		break;
    }
}
Example #2
0
/*
 GET AND PRINT IP ADDRESS
*/
int GetIP(void)
{
	char *hostname = "www.google.com"; /*Host/domain name*/
	char ip[100]; /*List of Allias'*/
	struct hostent *he;
	struct in_addr **addr_list;
	int i;

	InitSock();

	//fetches IP of domain name
	if ((he = gethostbyname(hostname)) == NULL)
	{
		//gethostbyname failled
		printf("gethostbyname failed: %d", WSAGetLastError());
		return 1;
	}

	//Cast the h_addr_list to in_addr, since h_addr_list also has the ip in long format only
	addr_list = (struct in_addr **) he -> h_addr_list;

	for (i = 0; addr_list[i] != NULL; ++i)
	{
		//Reeturn the first one
		strcpy(ip, inet_ntoa(*addr_list[i])); //from long to dotted format, opposite of inet_addr
	}

	printf("%s resolved to: %s\n", hostname, ip);

	getchar();

	return 0;
}
Example #3
0
// ZThread Entry This function is called when the thread is created in Master.cpp (mangosd)
void IRCClient::run()
{
    // Before we begin we wait a while MaNGOS is still starting up.
    ACE_Based::Thread::Sleep(500);

    /* Connection count
     */
    int cCount = 0;

    // Create a loop to keep the thread running untill active is set to false
    while (m_bActive && !World::IsStopped())
    {
        // Initialize socket library
        if (InitSock())
        {
            // Connect To The IRC Server
            sLog.outString("MangChat: Connecting to %s Try # %d", m_sHost.c_str(), cCount);

            if (Connect(m_sHost.c_str(), m_iPort))
            {
                sLog.outString("MangChat: Connected And Logging In");

                // On connection success reset the connection counter
                cCount = 0;

                // Login to the IRC server
                if (Login(m_sNick, m_sUser, m_sPass))
                {
                    sLog.outString("MangChat: Logged In And Running!!");

                    // While we are connected to the irc server keep listening for data on the socket
                    while (m_bConnected && !World::IsStopped())
                    {
                        SockRecv();
                    }
                }

                sLog.outString("MangChat: Connection To IRC Server Lost!");
            }

            // When an error occures or connection lost cleanup
            Disconnect();

            // Increase the connection counter
            ++cCount;

            // if MAX_CONNECT_ATTEMPT is reached stop trying
            if (cCount == MAX_CONNECT_ATTEMPT)
                m_bActive = false;

            // If we need to reattempt a connection wait WAIT_CONNECT_TIME milli seconds before we try again
            if (m_bActive)
                ACE_Based::Thread::Sleep(WAIT_CONNECT_TIME);
        }
        else
        {
            // Socket could not initialize cancel
            m_bActive = false;
            sLog.outError("MangChat: Could not initialize socket");
        }
    }
    // thread stays alive for calls from other threads
}
Example #4
0
// ZThread Entry This function is called when the thread is created in Master.cpp (mangosd)
void IRCClient::run()
{
    sIRC.iLog.WriteLog(" %s : ****** MaNGOS With MangChat Has Been Started ******", sIRC.iLog.GetLogDateTimeStr().c_str());

    // Before we begin we wait a while MaNGOS is still starting up.
    ACE_Based::Thread::Sleep(500);
    sLog.outString("\n%s\n%s\n%s\n%s",
        "***************************************",
        "**   MangChat Threaded IRC Client    **",
        "**         for MangosR2              **",
        "***************************************");
    sLog.outString("MangChat: %s", sIRC._Mver.c_str());
    int cCount = 0;

    // Clean Up MySQL Tables
    sLog.outString("MangChat: Cleaning Up Inchan Table");
    WorldDatabase.PExecute("DELETE FROM `IRC_Inchan`");
    sIRC._Max_Script_Inst = 0;

    // Create a loop to keep the thread running untill active is set to false
    while(sIRC.Active && !World::IsStopped())
    {
        // Initialize socket library
        if (InitSock())
        {
            // Connect To The IRC Server
            sLog.outString("MangChat: Connecting to %s Try # %d", sIRC._Host.c_str(), cCount);
            if(this->Connect(sIRC._Host.c_str(), sIRC._Port))
            {
                // On connection success reset the connection counter
                cCount = 0;
                sLog.outString("MangChat: Connected And Logging In");
                // Login to the IRC server
                if(this->Login(sIRC._Nick, sIRC._User, sIRC._Pass))
                {
                    sLog.outString("MangChat: Logged In And Running!!");
                    // While we are connected to the irc server keep listening for data on the socket
                    while(sIRC.Connected && !World::IsStopped()){ sIRC.SockRecv(); }
                }
                sLog.outString("MangChat: Connection To IRC Server Lost!");
            }
            // When an error occures or connection lost cleanup
            Disconnect();
            // Increase the connection counter
            cCount++;
            // if MAX_CONNECT_ATTEMPT is reached stop trying
            if(sIRC._MCA && cCount == sIRC._MCA)
                sIRC.Active = false;
            // If we need to reattempt a connection wait WAIT_CONNECT_TIME milli seconds before we try again
            if(sIRC.Active)
                ACE_Based::Thread::Sleep(sIRC._wct);
        }
        else
        {
            // Socket could not initialize cancel
            sIRC.Active = false;
            sLog.outError("MangChat: Could not initialize socket");
        }
    }
    // thread stays alive for calls from other threads
}
Example #5
0
extern "C" _declspec(dllexport) int __stdcall Connect(const char* ipAddr,int nPort)

{
	try
	{



		TRACE("调用Connect");

		if (GetSockStatus()==0)
		{
			return 30003;
		}


		///////////////////////////////////////////////

		CString cstr_ipaddr;
		int ret=0;
		ret=NameAddressConvert(ipAddr,&cstr_ipaddr);
		if (ret==0)
		{
           TRACE("NameAddressConvert 转换成功 地址 %s",cstr_ipaddr);
		}
		else
		{
              return ret;
		}


		///////////////////////////////////////////////

		InitSock();   
		g_socketServer=socket(AF_INET,SOCK_STREAM,0);   
		if (g_socketServer == INVALID_SOCKET)   
		{   
			UnInitSock();   
			return GetLastError();   
		}   
		sockaddr_in sin;   
		sin.sin_addr.S_un.S_addr=inet_addr((const char*)cstr_ipaddr);   
		sin.sin_family=AF_INET;   
		sin.sin_port=htons(nPort);     
		int iret;


		while(true)
		{  

			iret=connect(g_socketServer,(sockaddr*)&sin,sizeof(sockaddr));
			if (iret == SOCKET_ERROR)   
			{   iret=WSAGetLastError();

			if (iret==WSAEISCONN)
			{
				break;
			}


			if ((iret !=  WSAEWOULDBLOCK)&&(iret!=WSAEALREADY))
			{
				UnInitSock();   
				return iret;  
			}


			}
			else
			{
				break;
			}
		}

		BOOL iKeepAlive=SetNetWorkKeepAlive(g_socketServer);
		if (iKeepAlive==TRUE)
		{
			TRACE("SetNetWorkKeepAlive TRUE");
			TRACE("SetNetWorkKeepAlive TRUE");
		}
		else
		{
			TRACE("SetNetWorkKeepAlive FALSE");
			TRACE("SetNetWorkKeepAlive FALSE");

		}




		g_wsaEvent=::WSACreateEvent();   
		::WSAEventSelect(g_socketServer,g_wsaEvent,FD_READ|FD_WRITE|FD_CLOSE);   

		pThreadParam = new ST_THREAD_PARAM();   
		pThreadParam->socket = g_socketServer;   
		pThreadParam->wsaEvent = g_wsaEvent;   

		global_socket=new CClientSocket();
		////////////////////////////////////////////////////////////
		//pCWinThread= AfxBeginThread(ServiceThread, pThreadParam);
		hThread = ::CreateThread(NULL,0,ServiceThread,(LPVOID)pThreadParam,0,NULL);  
		//hThread =(HANDLE) _beginthreadex(NULL,0,ServiceThread,(LPVOID)pThreadParam,0,NULL);  
		///////////////////////////////////////////////////////
		if (hThread == INVALID_HANDLE_VALUE)   
		{   
			TRACE("Failed to create new thread...\n");   
			UnInitSock();   
			return GetLastError();   
		} 

		//CloseHandle(hThread);
		TRACE("threadid---- %d",hThread);
		return 0;



	}
	catch (CMemoryException* e)
	{
		return 30050;
	}
	catch (CFileException* e)
	{
		return 30051;

	}
	catch (CException* e)
	{
		return 30052;
	}
	catch(...)
	{
        return 30053;
	}
	

}
Example #6
0
int main(int argc, char** argv)
{
    signal(SIGINT, IntHandler);

    Server serv;

    // Initialize the server
    InitConfig(&serv.conf, argv[1], argc, argv);
    
    if(!serv.conf.name) {
        fprintf(stderr, "Script doesn't specify a server name.\n");
        return 1;
    }

    if(!serv.conf.port) {
        fprintf(stderr, "Script doesn't specify a port.\n");
        return 1;
    }

	printf("Successfully configured server.\n"
		"Name: %s\n"
		"Port: %s\n"
		"Num Threads: %d\n"
		"Cycles Per Loop: %d\n"
		"Num Routes: %d\n", serv.conf.name, serv.conf.port, serv.conf.numThreads, serv.conf.cyclesPerLoop, sb_count(serv.conf.routes));

    InitList(&serv.clientQueue, sizeof(Sock));
    InitList(&serv.requestQueue, sizeof(ClientRequest));

    cnd_init(&serv.updateLoop);
    cnd_init(&serv.newConn);

    // The loop thread is responsible for initializing LoopData

    thrd_t loopThread, connThread;

    thrd_create(&loopThread, MainLoop, &serv);
    thrd_create(&connThread, ConnLoop, &serv);

    // Initialize winsock and listen for clients
    WSADATA wsaData;
    SOCKET listenSocket;

    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if(iResult != 0) {
        fprintf(stderr, "WSAStartup failed: %d\n", iResult);
        return 1;
    }

    struct addrinfo hints;
    
    ZeroMemory(&hints, sizeof(hints));

    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    struct addrinfo* result;

    iResult = getaddrinfo(NULL, serv.conf.port, &hints, &result);
    if(iResult != 0) {
        fprintf(stderr, "getaddrinfo failed: %d\n", iResult);
        WSACleanup();
        return 1;
    }
    
    listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

    if(listenSocket == INVALID_SOCKET) {
        fprintf(stderr, "Error at socket(): %d\n", WSAGetLastError());
        freeaddrinfo(result); 
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = bind(listenSocket, result->ai_addr, (int)result->ai_addrlen);

    if(iResult == SOCKET_ERROR) {
        fprintf(stderr, "bind failed with error: %d\n", WSAGetLastError());
        closesocket(listenSocket);
        WSACleanup();
        return 1;
    }

    if(listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
        fprintf(stderr, "listen failed with error: %d\n", WSAGetLastError());
        closesocket(listenSocket);
        WSACleanup();
        return 1;
    }
	
	while (KeepRunning) {
		SOCKET clientSocket = accept(listenSocket, NULL, NULL);

		if (clientSocket == INVALID_SOCKET) {
			fprintf(stderr, "accept failed: %d\n", WSAGetLastError());
            continue;
		}

		int iMode = 1;
        if (ioctlsocket(clientSocket, FIONBIO, &iMode) == SOCKET_ERROR) {
            fprintf(stderr, "ioctlsocket failed: %d\n", WSAGetLastError());
            continue;
        }

        Sock sock;

        InitSock(&sock, (void*)clientSocket);
        
        ListPushBack(&serv.clientQueue, &sock);

        cnd_signal(&serv.newConn);
	}

    WSACleanup();

    thrd_join(&connThread, NULL);
	thrd_join(&loopThread, NULL);

    cnd_destroy(&serv.newConn);
    cnd_destroy(&serv.updateLoop);

	DestroyList(&serv.requestQueue);
	DestroyList(&serv.clientQueue);

    DestroyConfig(&serv.conf);

	return 0;
}
Example #7
0
/*
	Can only do one connection at a time, stays open
*/
int main(void)
{
	/*
	Servers need to:
	*Open a socket
	*Bind to an address(and port)
	*listen for incoming connections
	*accept connections
	*read/send
	*/

	SOCKET s, new_socket;
	struct sockaddr_in server, client;
	int c; //takes size of sockaddr_in for client socket
	char *message;

	InitSock();


	//Create a Socket
	if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
	{
		printf("Could not create socket: %d", WSAGetLastError());
	}

	printf("Socket Created\n");

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons(8888);

	//Bind
	if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
	{
		printf("Bind failed with error code: %d", WSAGetLastError());
	}

	printf("Bind done\n");

	//Listen for socket
	listen(s, 3);
	/* Then accept the connection */

	//accept and incominf connection
	printf("Waiting for incoming connections...\n");

	c = sizeof(struct sockaddr_in);
	while ((new_socket = accept(s, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
	{
		printf("Connection accepted\n");

		//Reply to client
		message = "Hello, you!";
		send(new_socket, message, strlen(message), 0);
	}

	if (new_socket == INVALID_SOCKET)
	{
		printf("accept failed with error code: %d", WSAGetLastError());
	}

	getchar(); //pause

	closesocket(s);
	WSACleanup();

	return 0;

}
Example #8
0
/*
 BASIC SOCKET CONNECTION. SENDS/RCEIVES FROM AN IP
*/
int basicSocket()
{
	/*
	TCP/SOCK_STREAM: CONNECTION BASED - UNINTERRUPTED STREAM OF INFORMATION
	UDP/SOCK_DGRAM: NON-CONNECTION BASED - SENDING AND RECIEVING PACKETS FROM ANYONE AND EVERYONE (similiar to ICMP, ARP)
	*/
	SOCKET s;
	struct sockaddr_in server;//need IP and port number to remote connect
	char* message, server_reply[2000];
	int recv_size;

	InitSock(); //Initillises winsock

	//Create Socket
	if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) //socket() creates socket and returns descriptor which can be used in other network commands
	{
		printf("Could not create socket: %d\n", WSAGetLastError());
		/*
		Creates a socket of:
		Address Family: AF_INET (IPv4)
		Type: SOCK_STREAM (This means connection orientated TCP Protocol), SOCK_DGRAM indicates UDP of non-connection
		Protocol: 0 (or IPPROTO_TCP, IPPROTO_UDP)
		*/
		exit(1);
	}

	printf("Socket Created\n\n");

	//Setup connection information
	server.sin_addr.s_addr = inet_addr("216.58.208.142"); //converts IP to long format and stores inside server struct (IP is for google.com)
	server.sin_family = AF_INET; //address family
	server.sin_port = htons(80); // connect on port

	//connect to remote server
	if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
	{
		printf("connection error: %d", WSAGetLastError());
		getchar();
		return 1;
	}

	printf("Connected\n");

	//Send data
	message = "GET / HTTP/1.1\r\n\r\n";

	if (send(s, message, strlen(message), 0) < 0)
	{
		printf("Send Failed");
		getchar();
		exit(1);
	}

	printf("Data Sent\n");

	//Receive a reply fromm server
	if ((recv_size = recv(s, server_reply, 2000, 0)) == SOCKET_ERROR)
	{
		puts("recv failed");
	}

	printf("Reply received\n");

	//Add Termminating character to make it a proper string
	server_reply[recv_size-1] = '\0';
	printf("%s", server_reply);

	getchar(); //pause

	closesocket(s);
	WSACleanup();

	return 0;
}