2013년 2월 28일 목요일

pe format


코드섹션
.text
데이터섹션
.data <- 데이터코드
.rdata <- 일기전용 데이터 코드
.idata <- 임포트데이터

[ctrl]+[esc]

시작메뉴 팝업

2013년 2월 27일 수요일

seh


16:   {
00401070   push        ebp
00401071   mov         ebp,esp
00401073   push        0FFh
00401075   push        offset string "1: Raise an Exception\n"+20h (0042f080)
0040107A   push        offset __except_handler3 (004083e4)
0040107F   mov         eax,fs:[00000000]
00401085   push        eax
00401086   mov         dword ptr fs:[0],esp
0040108D   add         esp,0B8h
00401090   push        ebx
00401091   push        esi
00401092   push        edi
00401093   mov         dword ptr [ebp-18h],esp
00401096   lea         edi,[ebp-58h]
00401099   mov         ecx,10h
0040109E   mov         eax,0CCCCCCCCh
004010A3   rep stos    dword ptr [edi]
17:       __try
004010A5   mov         dword ptr [ebp-4],0
18:       {
19:           __try{
004010AC   mov         dword ptr [ebp-4],1
20:               printf("1: Raise an Exception\n");
004010B3   push        offset string "1: Raise an Exception\n" (0042f060)
004010B8   call        printf (00408270)
004010BD   add         esp,4
21:               RAISE_AN_EXCEPTION();
004010C0   call        @ILT+0(RAISE_AN_EXCEPTION) (00401005)
22:           }
004010C5   mov         dword ptr [ebp-4],0
004010CC   call        $L8443 (004010d3)
004010D1   jmp         $L8446 (004010e1)
23:           __finally
24:           {
25:               printf("2: In Finally\n");
004010D3   push        offset string "2: In Finally\n" (0042f04c)
004010D8   call        printf (00408270)
004010DD   add         esp,4
$L8444:
004010E0   ret
26:           }
27:       }
004010E1   mov         dword ptr [ebp-4],0FFFFFFFFh
004010E8   jmp         $L8440+17h (0040110f)
28:       __except( printf("3: In Filter\n"))
004010EA   push        offset string "3: In Filter\n" (0042f03c)
004010EF   call        printf (00408270)
004010F4   add         esp,4
$L8441:
004010F7   ret
$L8440:
004010F8   mov         esp,dword ptr [ebp-18h]
29:       {
30:           printf("4: In Exception Handler\n");
004010FB   push        offset string "4: In Exception Handler\n" (0042f01c)
00401100   call        printf (00408270)
00401105   add         esp,4
31:       }
00401108   mov         dword ptr [ebp-4],0FFFFFFFFh
32:       return 0;
0040110F   xor         eax,eax
33:   }
00401111   mov         ecx,dword ptr [ebp-10h]
00401114   mov         dword ptr fs:[0],ecx
0040111B   pop         edi
0040111C   pop         esi
0040111D   pop         ebx
0040111E   add         esp,58h
00401121   cmp         ebp,esp
00401123   call        __chkesp (00408230)
00401128   mov         esp,ebp
0040112A   pop         ebp
0040112B   ret

2013년 2월 23일 토요일

[win32api] CreateWindow()


HWND CreateWindow(
  LPCTSTR lpClassName,    // 등록된 윈도우 클래스 이름
  LPCTSTR lpWindowName, // 윈도우 캡션 이름
  DWORD dwStyle,              // 윈도우 스타일
  int x,                               // 윈도우 좌측 상단의 x 좌표
  int y,                               // 윈도우 좌측 상단의 y 좌표
  int nWidth,                       // 윈도우 폭
  int nHeight,                      // 윈도우 높이  HWND hWndParent,          // 부모 윈도우의 핸들
  HMENU hMenu,               // 메뉴 또는 자식 윈도우 식별자
  HINSTANCE hInstance,     // 윈도우를 생성한 인스턴스 핸들
  LPVOID lpParam               // CREATESTRUCT 구조체를 통해 전달되는 값
);

2013년 2월 20일 수요일

execve()


#include 
#include 
#include 


int main( int ac, char* av[] )
{
   char *name[2];
   name[0] = "pass.exe";
   name[1] = 0;
 execve(name[0], name, NULL);
}

2013년 2월 18일 월요일

[c++/win32api]메모장

// MM4.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "resource.h"

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;        // current instance
TCHAR szTitle[MAX_LOADSTRING];        // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];        // The title bar text

// Foward declarations of functions included in this code module:
ATOM    MyRegisterClass(HINSTANCE hInstance);
BOOL    InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
  // TODO: Place code here.
 MSG msg;
 HACCEL hAccelTable;

 // Initialize global strings
 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
 LoadString(hInstance, IDC_MM4, szWindowClass, MAX_LOADSTRING);
 MyRegisterClass(hInstance);

 // Perform application initialization:
 if (!InitInstance (hInstance, nCmdShow)) 
 {
  return FALSE;
 }

 hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_MM4);

 // Main message loop:
 while (GetMessage(&msg, NULL, 0, 0)) 
 {
  if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
  {
   TranslateMessage(&msg);
   DispatchMessage(&msg);
  }
 }

 return msg.wParam;

 
// 메시지 루프
 while (GetMessage(&msg, NULL, 0, 0))
 {
  TranslateMessage(&msg); // 키보드 메시지를 번역
  DispatchMessage(&msg);  // 메시지를 해당 윈도우 프로시저로 보냅니다.
 }
 return msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage is only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
 WNDCLASSEX wcex;

 wcex.cbSize = sizeof(WNDCLASSEX); 

 wcex.style   = CS_HREDRAW | CS_VREDRAW;
 wcex.lpfnWndProc = (WNDPROC)WndProc;
 wcex.cbClsExtra  = 0;
 wcex.cbWndExtra  = 0;
 wcex.hInstance  = hInstance;
 wcex.hIcon   = LoadIcon(hInstance, (LPCTSTR)IDI_MM4);
 wcex.hCursor  = LoadCursor(NULL, IDC_ARROW);
 wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
 wcex.lpszMenuName = (LPCSTR)IDC_MM4;
 wcex.lpszClassName = szWindowClass;
 wcex.hIconSm  = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

 return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HANDLE, 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(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }
SLWA pSetLayeredWindowAttributes = NULL;  // 함수포인터 선언, 초기화.
 HINSTANCE hmodUSER32 = LoadLibrary("USER32.DLL"); // 인스턴스 얻음.
 pSetLayeredWindowAttributes=(SLWA)GetProcAddress(hmodUSER32,"SetLayeredWindowAttributes");    
 //함수포인터 얻음.
  SetWindowLong(hWnd, GWL_EXSTYLE,GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
 pSetLayeredWindowAttributes(hWnd, 0, (255 * 50) / 100, LWA_ALPHA);

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  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 iMessage,WPARAM wParam,LPARAM lParam)
{
 static char str[100];
 
 static int count, yPos;
 static SIZE size;
 HDC hdc;
 PAINTSTRUCT ps;
 switch(iMessage) {
 
 case WM_CREATE:
  count = 0;
  yPos = 0;
  CreateCaret(hWnd, NULL, 5, 15);
  ShowCaret(hWnd);
  break;
 case WM_PAINT: 
  /*
  hdc = BeginPaint(hWnd, &ps);
  TextOut(hdc,0,0,"helloWorld",10);
  EndPaint(hWnd, &ps);
  */
  hdc = BeginPaint(hWnd, &ps);
  GetTextExtentPoint(hdc,str, strlen(str), &size);
  TextOut(hdc,0,yPos,str,strlen(str));
  SetCaretPos(size.cx, 0);
  EndPaint(hWnd, &ps);
  break;
 /*
 case WM_KEYDOWN:
  hdc = GetDC(hWnd);
  TextOut(hdc,100,0,"KeyDown",7);
  ReleaseDC(hWnd, hdc);
  break;
 */
 /* 
 case WM_KEYUP:
  hdc = GetDC(hWnd);
  TextOut(hdc,200,0,"KeyUP",5);
  ReleaseDC(hWnd, hdc);
  break;
 */
 case WM_CHAR:
  
  if(wParam == VK_BACK) //backspace key
   count--;
  else if(wParam == VK_RETURN) //enter key
  {
   count = 0;
   yPos +=20;
  }
  else 
   str[count++] = wParam;
  
  str[count] = '\0';
  /*
  hdc = GetDC(hWnd);
  TextOut(hdc,300,0,str,strlen(str));
  ReleaseDC(hWnd, hdc);
  */
  InvalidateRgn(hWnd, NULL, TRUE);
  break;
 case WM_DESTROY:
  HideCaret(hWnd);
  DestroyCaret();
  PostQuitMessage(0);
  return 0;
 }
 return(DefWindowProc(hWnd,iMessage,wParam,lParam));
}

 

2013년 2월 17일 일요일

파일 각 라인 왼쪽 문자 제거

#!/usr/bin/perl

#Specify the file
$file = "key.txt";
#Open the file and read data
#Die with grace if it fails
open (FILE, "<$file") or die "Can't open $file: $!\n";
@lines = ;
open (DATA, '>>data.txt');
foreach ( @lines ) {
print $_;
#$_ =~ s/^d{3}//;
$_=substr($_,4);
print DATA $_;
}
#Finish up
close FILE;
close DATA;

2013년 2월 16일 토요일

m_hWnd


CWnd::m_hWnd

Visual Studio 2005
이 항목은 아직 평가되지 않았습니다.이 항목 평가
The handle of the Windows window attached to this CWnd.
HWND m_hWnd;
The m_hWnd data member is a public variable of type HWND.

2013년 2월 15일 금요일

[c/c++]파일복사

// 아래의 예제는 파일을 fread()와 fwrite()를 이용한
// 파일 복사를 하는 예입니다.

#include 

int main( void)
{
   FILE    *fp_sour;    // 파일 원본을 위한 파일 스트림 포인터
   FILE    *fp_dest;    // 복사 대상을 위한 파일 스트림 포인터
   char     buff[1024]; // 파일 내요을 읽기/쓰기를 위한 버퍼
   size_t   n_size;     // 읽거나 쓰기를 위한 데이터의 개수
                                          
   fp_sour  = fopen( "./main.c"  , "r");
   fp_dest  = fopen( "./main.bck", "w");
                            
   while( 0 < (n_size = fread( buff, 1, 1024, fp_sour)))
   {
      fwrite( buff, 1, n_size, fp_dest);
   }                            

   fclose( fp_sour);
   fclose( fp_dest);
   return 0;
}

2013년 2월 13일 수요일

dir

http://www.dreamincode.net/forums/topic/59943-accessing-directories-in-cc-part-i/
#include  // directory header
#include  // printf()
#include  // exit()

int main () // entry point of the program
{
    // first off, we need to create a pointer to a directory
    DIR *pdir = NULL; // remember, it's good practice to initialise a pointer to NULL!
    struct dirent *pent = NULL;

    // I used the current directory, since this is one which will apply to anyone reading
    // this tutorial~ If I said "C:\\" and you're on Linux, it may get a little confusing!
    pdir = opendir ("."); // "." will refer to the current directory
    if (pdir == NULL) // if pdir wasn't initialised correctly
    { // print an error message and exit the program
        printf ("\nERROR! pdir could not be initialised correctly");
        exit (3);
    } // end if

    while (pent = readdir (pdir)) // while there is still something in the directory to list
    {
        if (pent == NULL) // if pent has not been initialised correctly
        { // print an error message, and exit the program
            printf ("ERROR! pent could not be initialised correctly");
            exit (3);
 }
 // otherwise, it was initialised correctly. let's print it on the console:
        printf ("%s\n", pent->d_name);
    }
    // finally, let's close the directory
    closedir (pdir);
return 0;

// everything went OK
}

1


2013년 2월 7일 목요일

winsock2 socket

// winhide.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "resource.h"

#include 

using namespace std;

#define MAX_LOADSTRING 100
#define DEFAULT_PORT 80

// Global Variables:
HINSTANCE hInst;        // current instance
TCHAR szTitle[MAX_LOADSTRING];        // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];        // The title bar text

// Foward declarations of functions included in this code module:
ATOM    MyRegisterClass(HINSTANCE hInstance);
BOOL    InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
  // TODO: Place code here.
 MSG msg;
 HACCEL hAccelTable;

 // Initialize global strings
 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
 LoadString(hInstance, IDC_WINHIDE, szWindowClass, MAX_LOADSTRING);
 MyRegisterClass(hInstance);

 // Perform application initialization:
 if (!InitInstance (hInstance, nCmdShow)) 
 {
  return FALSE;
 }

 hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_WINHIDE);

 // Main message loop:
 while (GetMessage(&msg, NULL, 0, 0)) 
 {
  if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
  {
   TranslateMessage(&msg);
   DispatchMessage(&msg);
  }
 }

 return msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage is only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
 WNDCLASSEX wcex;

 wcex.cbSize = sizeof(WNDCLASSEX); 

 wcex.style   = CS_HREDRAW | CS_VREDRAW;
 wcex.lpfnWndProc = (WNDPROC)WndProc;
 wcex.cbClsExtra  = 0;
 wcex.cbWndExtra  = 0;
 wcex.hInstance  = hInstance;
 wcex.hIcon   = LoadIcon(hInstance, (LPCTSTR)IDI_WINHIDE);
 wcex.hCursor  = LoadCursor(NULL, IDC_ARROW);
 wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
 wcex.lpszMenuName = (LPCSTR)IDC_WINHIDE;
 wcex.lpszClassName = szWindowClass;
 wcex.hIconSm  = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

 return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HANDLE, 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(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, SW_SHOW);
   UpdateWindow(hWnd);

   hisocket();

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  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;
 PAINTSTRUCT ps;
 HDC hdc;
 TCHAR szHello[MAX_LOADSTRING];
 LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);

 switch (message) 
 {
  case WM_COMMAND:
   wmId    = LOWORD(wParam); 
   wmEvent = HIWORD(wParam); 
   // Parse the menu selections:
   switch (wmId)
   {
    case IDM_ABOUT:
       DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
       break;
    case IDM_EXIT:
       DestroyWindow(hWnd);
       break;
    default:
       return DefWindowProc(hWnd, message, wParam, lParam);
   }
   break;
  case WM_PAINT:
   hdc = BeginPaint(hWnd, &ps);
   // TODO: Add any drawing code here...
   RECT rt;
   GetClientRect(hWnd, &rt);
   DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER);
   EndPaint(hWnd, &ps);
   break;
  case WM_DESTROY:
   PostQuitMessage(0);
   break;
  default:
   return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}

// Mesage handler for about box.
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
 switch (message)
 {
  case WM_INITDIALOG:
    return TRUE;

  case WM_COMMAND:
   if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) 
   {
    EndDialog(hDlg, LOWORD(wParam));
    return TRUE;
   }
   break;
 }
    return FALSE;
}


int hisocket() {

    //----------------------
    // Declare and initialize variables.
    int iResult;
    WSADATA wsaData;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService;

    int recvbuflen = DEFAULT_BUFLEN;
    string request;
 request += "GET / HTTP/1.1 \r\n";
 request += "Host:www.naver.com\r\n";
 request += "\r\n";
 
 char recvbuf[DEFAULT_BUFLEN] = "";

    //----------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
    //    wprintf(L"WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
      //  wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.
    clientService.sin_family = AF_INET;
   // clientService.sin_addr.s_addr = inet_addr( "180.70.134.19" );
    clientService.sin_port = htons(DEFAULT_PORT);
 
 struct hostent* g_szIpAddress;
 g_szIpAddress = gethostbyname("www.naver.com");
    clientService.sin_addr.s_addr=*(LPDWORD)g_szIpAddress->h_addr_list[0];
    
    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if (iResult == SOCKET_ERROR) {
        //wprintf(L"connect failed with error: %d\n", WSAGetLastError() );
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
  }

    //----------------------
    // Send an initial buffer
    iResult = send( ConnectSocket, request.c_str(), request.length(), 0 );
    if (iResult == SOCKET_ERROR) {
      //  wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

   // printf("Bytes Sent: %d\n", iResult);

   // Receive until the peer closes the connection
 FILE *fd;
    fd=fopen("receved.txt","w+");

 do{
 iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    int i;

 //받은파일 내용 출력/저장.
 for(i=0; i <=iResult ; i++)
 {
   fprintf(fd,"%c", recvbuf[i]);
 }
 
 } while (iResult>0);

    // close the socket
    iResult = closesocket(ConnectSocket);
    if (iResult == SOCKET_ERROR) {
      //  wprintf(L"close failed with error: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    WSACleanup();
    return 0;
}

베르누이식


유체역학은 기본적으로 뉴턴 역학에 기초를 두고 있다. 따라서 베르누이 방정식을 유도하기 위해서, 흐름관 단면 내의 유체에 일-에너지 정리를 이용하여 유도 가능하다.
<베르누이 방정식 유도>
어떤 시간에 두 단면 a와 c 사이에 놓여 있는 유체를 고려한다. 낮은 쪽 끝에서 유체의 속력이 이고 압력은 이다. 그리고 임의의 짧은 시간 간격 dt 동안 초기에 a에 이던 유체는 b 까지, 거리 를 움직인다. 이때 같은 시간 간격 동안 c에 있던 유체는 d 까지 거리 를 움직인다.
양 끝에서 단면적은 보는 바와 같이 와 이며, 연속적인 관계 때문에 dt 동안 두 단면을 통과하는 유체의 부피는 이다.
이제 dt 동안 이 유체에 한 일을 계산해 보자. a에서 단명에 작용하는 힘은 이고, c에서 힘은이다. 여기서 과 는 양 끝에서의 압력이다. 따라서 이 변위 동안에 한 일의 양 dW
이다. 여기서 음의 부호는 c에서 힘은 변위가 반대 방향이기 때문이다.
이 일을 이제, 유체소에 대한 역학적 에너지 즉, 운동에너지와 위치에너지에 관해 서술해 보자.
단면 b와 c사이의 유체에 대한 역학적 에너지는 변하지 않는다. dt시간 초기에 a와 b 사이의 유체는 부피가 , 질량이  그리고 운동에너지는 이다. 마찬가지로 c와 d 사이에서 유체의 운동에너지는 이다. 따라서 이 시간동안 운동에너지의 총 변화 dK
이다. 동일한 방법을 적용하여 위치에너지의 변화 dU를 구하면
이다. 운동량의 변화량과 위치에너지의 변화량의 합은 총 한 일의 변화량과 같음으로dW=dK+dU에 각각 대입하면 다음을 얻을 수 있다.
이것이 베르누이 방정식이다.

연속방정식 $$
A_{1}v_{1}=A_{2}v_{2}

$$
역학적 에너지 보존
$$
\\P_{2}V_{2}-P_{1}V_{1}=\frac{1}{2}\rho V_{2}v_{2}^{2}-\frac{1}{2}\rho V_{1}v_{1}^{2}
$$
연속방정식을 대입하여 정리
$$
\\P_{2}-P_{1}\frac{V_{2}}{V_{1}}=\frac{1}{2}\rho v_{2}^{2}-\frac{1}{2}\rho \frac{V_{2}}{V_{1}v_{1}^{2}}
$$

2013년 2월 6일 수요일

perl socket another

use Socket;
use FileHandle;

$iaddr = inet_aton($ARGV[0]);
$paddr = sockaddr_in($ARGV[1],$iaddr);

$proto = getprotobyname("tcp");

socket (FHOST, PF_INET, SOCK_STREAM, $proto) or
                 die ("no free sockets\n");
connect (FHOST, $paddr)  or
                 die ("$ARGV[0] is not responding\n");

# turn buffering off

autoflush FHOST 1;

# dialogue

print FHOST "GET / HTTP/1.1 
Host:www.naver.com\n\n";

@response = ;

$rpage = join("",@response);
$rpage =~ s/\r\n/\n/g;
$rpage =~ s/\r/\n/g;
($header,$page) = split(/\n\n/,$rpage,2);
print $header;
@tags = ($page =~ /<(.*?)>/gs);

foreach (@tags) {
        s/\s*=\s*/=/g;
        @params = split(/\s+/);
        $type = lc(shift @params);
        next if ($type ne "a");
        foreach $f(@params) {
                ($name,$val)=split(/=/,$f,2);
                next if (lc($name) ne "href");
                $val =~ s/^"(.*)"$/$1/;
                push @linx,$val;
                }
        }

perl socket

#!/usr/bin/perl -w
use strict;

use IO::Socket;

my $host = "www.naver.com";
my $header = "GET / HTTP/1.1 
Host:www.naver.com\n\n";

my $remote = IO::Socket::INET->new( Proto     => "tcp",
                                 PeerAddr  => $host,
                                 PeerPort  => "http(80)",
                                );
unless ($remote) { die "cannot connect to http daemon on $host" }
$remote->autoflush(1);
print "--------- HTTP REQUEST to $host --------\n";
print $header;
print "--------- HTTP RESPONSE from $host --------\n";
print $remote $header;

while ( <$remote> ) { print }
close $remote;

2013년 2월 5일 화요일

2013년 2월 2일 토요일

임피던스 복소수

임피던스는 저항의 개념을 AC까지 확장한 개념인 것이다.
저항(R), 커패시터(C), 인덕터(L)를 지배하는 공식을 전압과 전류 관점으로 쓰면 다음과 같다.

                          (1)

임피던스를 정하기 위해 페이저(phasor)를 도입하자. 페이저는 다음과 같이 정의한다.

                                  (2)

                   (3)

식 (2)와 (3)을 이용해서 식 (1)의 미분기호를 d/dt ≡ jω로 바꾸면 다음을 얻는다. 

                                  (4)

신기하게도 식 (2)를 이용하면 식 (4)와 같이 저항(R), 커패시터(C), 인덕터(L) 종류와는 관계없이 AC에 대해 옴 법칙(Ohm's law)을 다음과 같이 일반화할 수 있다.

                                  (5)

페이저를 도입했기 때문에 임피던스는 복소수(complex number, 수학에서 복소수는 보통 z로 표기)로 표기한다. 그래서, 임피던스를 나타내는 문자는 Z를 사용한다.
임피던스 개념을 최초로 제안한 사람은 페이저의 창안자인 헤비사이드(Oliver Heaviside)이다. 헤비사이드는 은둔의 과학자답게 우리에게는 잘 알려져 있지 않지만 평생을 혼자 조용하게 연구하면서 페이저(phasor), 교류 회로이론(AC circuit theory), 라플라스 변환(Laplace transform), 맥스웰 방정식(Maxwell's equations), 전송선 이론(transmission line theory), 전리층(ionosphere), 도파관(waveguide), 포인팅의 정리(Poynting's theorem) 등의 개념을 최초로 제안하고 심도있게 발전시켰다. 현재 우리가 배우는 것의 대부분은 사실 헤비사이드의 머리에서 나왔다. 고등학교만 나온 헤비사이드를 이런 수준의 과학자로 만든 것은 맥스웰(James Clerk Maxwell)의 책[1]이었다. 1873년에 읽은 맥스웰의 책에 감동받은 헤비사이드는 자신의 인생을 전자파에 바치기로 하였다. 얼마뒤 회사까지 그만두고 부모님의 집에서 결혼도 하지 않은 채 평생을 전자파 연구에 매진했다.

                         (6)

                         (7)

임피던스 개념을 사용하면 커패시터와 인덕터를 이용해 일반화한 식 (6)의 KCL(Kirchhoff Current Law)과 식 (7)의 KVL(Kirchhoff Voltage Law)을 DC와 유사하게 아래와 같이 표현할 수 있다.

                         (8)

임피던스를 이용해 일반화 시킨 식 (8)의 AC 회로용 KCL과 KVL을 이용하면 직렬과 병렬회로의 등가 임피던스(equivalent impedance)를 쉽게 계산할 수 있다.
[그림 1] 직렬로 된 임피던스(출처: wikipedia.org)
[그림 2] 병렬로 된 임피던스(출처: wikipedia.org)

저항(resistor), 커패시터(capacitor), 인덕터(inductor)에 대한 등가 임피던스 유도를 참고하면 직렬과 병렬에 대한 등가 임피던스를 식 (9)와 (10)처럼 증명할 수 있다.

                         (9)

                         (10)

임피던스가 복소수인 것의 의미를 생각해 보자. [그림 3]과 같이 임피던스는 복소수이기 때문에 크기(magnitude)와 위상(phase)을 가진다.

 [그림 3] 임피던스의 복소평면 표현(출처: wikipedia.org)

임피던스의 크기가 의미하는 것은 전류 흐름을 방해하는 정도인 저항(resistance)을 뜻한다. 식 (4)에도 제시되어 있듯이 저항, 커패시터, 인덕터는 항상 저항을 가진다.
그 다음으로 중요한 것이 위상이다. 식 (5)를 크기와 위상으로 다시 표현하면 아래와 같다.

                         (11)

임피던스의 위상이 의미하는 것은 전류위상에 비해 전압위상이 차이나는 정도이다. 페이저 관점에서 전압과 전류의 위상은 임피던스의 위상만큼 차이가 나게 된다.
이를 이해하기 위해 [표 1]을 살펴보자.

[표 1] 주파수별 임피던스의 변화

저항 소자는 주파수가 아무리 바뀌어도 임피던스의 변화가 없다. 하지만, 인덕터와 커패시터는 식 (4)에 의해 주파수별로 임피던스 특성이 바뀌게 된다. 인덕터의 경우 주파수가 0(DC)으로 가면 단락(短絡, short)으로 작용해 임피던스가 없지만 주파수가 매우 커지면 거의 개방(開放, open)처럼 행동해 임피던스가 무한대(or 전류가 흐를 수 없는 상태)가 된다. 커패시터는 주파수가 0(DC)일 때는 개방이었다가 주파수가 높아질수록 단락과 유사한 상태가 된다.
또한, 관심있게 봐야하는 것은 임피던스의 위상이다. 식 (4)를 참고하면 저항은 위상차이를 만들어내지 못하지만 인덕터는 j(=90˚)만큼 커패시터는 -j(=-90˚ or 270˚)만큼의 위상차이를 만들어낸다. 즉, 전류위상을 0˚이라 가정하면 저항의 전압위상은 0˚, 인덕터의 전압위상은 90˚, 커패시터의 전압위상은 -90˚이 된다.

AC 회로이론에서는 새로운 개념들이 쏟아져 나오게 된다. 영어를 쓰는 미국인에게는 자명한 내용이지만 영어가 외국어인 우리에게는 외워야할 대상이다. 어쩌겠나 헤비사이드가 한국사람이 아닌 것을.

                         (12)

임피던스는 복소수기 때문에 실수부(R)와 허수부(X)로 나눌 수 있다. 임피던스의 실수부는 전류흐름을 방해하는 저항(resistance)을 의미하고 허수부는 에너지 저장과 관련된 리액턴스(reactance)를 뜻한다. 식 (4)에서 임피던스가 허수를 가질 수 있는 소자는 커패시터와 인덕터이다. 커패시터와 인덕터는 에너지를 전기와 자기 형태로 저장하는 소자이다. 그런데, 에너지 저장과 리액턴스는 무슨 관계인가? 리액턴스를 굳이 한글로 번역하면 '반발비율' 혹은 '반응비율'이다. 스프링(spring)과 같은 물건은 외부에서 힘을 주면 에너지를 저장했다가 다시 튕기는(or 반발하는) 능력이 있다. 마찬가지로 커패시터와 인덕터도 외부에서 전압이나 전류가 가해지면 에너지를 저장했다가 반드시 에너지를 방출하는 반발을 한다. 이런 의미에서 임피던스의 허수부는 리액턴스라는 이름이 붙어있다.
임피던스의 역수는 어드미턴스(admittance)라고 한다. 어드미턴스를 한글로 번역하면 '허용비율'이다. 즉, 전류를 잘 흐를 수 있도록 허용하는 비율이라는 의미이다. 어드미턴스의 실수부(G)는 컨덕턴스(coductance), 허수부(B)는 서셉턴스(susceptance)라고 한다. 이를 각각 한글로 번역하면 컨덕턴스는 전도비율, 서셉턴스는 허가비율이 된다. 서셉턴스라는 말이 생긴 이유는 리액턴스(반발비율)의 역수를 허락비율(permittance)로 표현하면서 부터이다. 반발과 허락을 영어로 표현하면 reactance, susceptance가 되니 영어로 생각하면 이런 복잡한 용어를 쉽게 외울 수 있다.

[참고문헌]
[1] J. C. MaxwellTreatise on Electricity and Magnetismvol. 1 and vol. 2, 1873.

2013년 2월 1일 금요일

서울시 대학생 알바


1차 반응의 반감기

1차반응의 반감기로부터 직접 속도상수를 구할 수 있다


$$ \[va = - \frac{-d[A]]}{dt} = k[A]\] \[ln\frac{1}{2} = kT\] \[k = \frac{ln2}{T}\] T는 그래프로부터 20s k = 0.035 = 3.5 * 10^-2
$$