// MyPortScaner.cpp : Defines the entry point for the application.
//


#include <WinSock2.h>
#include <CommCtrl.h>
#include <tchar.h>

#pragma comment(lib,"comctl32.lib")
#pragma comment(lib,"WS2_32.lib")

#define MAX_LOADSTRING 100
#define MAX_TEKST       300
#define ID_SCAN_BUTTON 1
#define ID_IPADDRESS   2
#define ID_MIN_RANGE   3
#define ID_MAX_RANGE   4
#define ID_LISTBOX     5

// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name
TCHAR tekst[MAX_TEKST];

// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);
BOOL PortScan(DWORD ip_addr, int port);

BOOL PortScan(DWORD ip_addr, int port)
{
	BOOL result = false;
	SOCKET gniazdo = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (gniazdo == INVALID_SOCKET)
	{
		MessageBox(NULL, TEXT("Error"), TEXT("Error creating socket"), MB_OK);
		return false;
	}

	sockaddr_in service;
	memset(&service, 0, sizeof(service));
	service.sin_family = AF_INET;
	service.sin_addr.s_addr = htonl(ip_addr);
	service.sin_port = htons(port);

	if (bind(gniazdo, (SOCKADDR *)& service, sizeof(service))) result = true;

	closesocket(gniazdo);
	shutdown(gniazdo, SD_BOTH);
	
	return result;
}

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	InitCommonControls();

	WSADATA wsaData;
	int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (err != 0) {
		MessageBox(NULL, TEXT("Error"), TEXT("WSAStartup failed"), MB_OK);
		return 1;
	}


	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	
	

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
	}
	WSACleanup();

	return (int) msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(NULL, IDI_APPLICATION); 
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= 0; 
	wcex.lpszClassName	= TEXT("Klasa okien");
	wcex.hIconSm		= LoadIcon(NULL, IDI_APPLICATION);

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(TEXT("Klasa okien"), szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, 260, 500, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent, minRange, maxRange;
	HWND ipadrr, list, button;
	DWORD ip_addr;
	
	switch (message)
	{

	case WM_CREATE:
		CreateWindow(WC_IPADDRESS, L"", WS_CHILD | WS_OVERLAPPED | WS_VISIBLE, 10, 10, 220, 25, 
			hWnd, (HMENU)ID_IPADDRESS, GetModuleHandle(NULL), NULL);
		CreateWindow(TEXT("EDIT"), TEXT("0"), WS_CHILD | WS_VISIBLE | WS_BORDER | ES_RIGHT,
			10, 45, 60, 25, hWnd, (HMENU)ID_MIN_RANGE, GetModuleHandle(NULL), NULL);
		CreateWindow(TEXT("EDIT"), TEXT("65532"), WS_CHILD | WS_VISIBLE | WS_BORDER | ES_RIGHT,
			80, 45, 60, 25, hWnd, (HMENU)ID_MAX_RANGE, GetModuleHandle(NULL), NULL);
		CreateWindow(WC_LISTBOX, TEXT(""), WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_BORDER,
			10, 80, 220, 350, hWnd, (HMENU)ID_LISTBOX, GetModuleHandle(NULL), NULL);
		CreateWindow(TEXT("BUTTON"), TEXT("Scan"), WS_CHILD | WS_VISIBLE ,
			150, 45, 80, 25, hWnd, (HMENU)ID_SCAN_BUTTON, GetModuleHandle(NULL), NULL);
		SendMessage(GetDlgItem(hWnd, ID_IPADDRESS), IPM_SETADDRESS, 0, MAKEIPADDRESS(127, 0, 0, 1));
		break;
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case ID_SCAN_BUTTON:
			SendMessage(GetDlgItem(hWnd, ID_IPADDRESS), IPM_GETADDRESS, 0, (LPARAM)&ip_addr);
			SendMessage(GetDlgItem(hWnd, ID_LISTBOX), LB_RESETCONTENT, 0, 0);
			GetWindowText(GetDlgItem(hWnd, ID_MIN_RANGE), tekst, MAX_TEKST);
			minRange = _ttoi(tekst);
			GetWindowText(GetDlgItem(hWnd, ID_MAX_RANGE), tekst, MAX_TEKST);
			maxRange = _ttoi(tekst);

			for (int i = minRange; i <= maxRange; i++)
			{
				if (PortScan(ip_addr, i))
				{
					_stprintf_s(tekst, MAX_TEKST, TEXT("IP: %d.%d.%d.%d, port: %d"), 
						FIRST_IPADDRESS(ip_addr), SECOND_IPADDRESS(ip_addr), THIRD_IPADDRESS(ip_addr), 
						FOURTH_IPADDRESS(ip_addr), i);
					SendMessage(GetDlgItem(hWnd, ID_LISTBOX), LB_INSERTSTRING, -1, (LPARAM)tekst);
				}		
			}
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}
