유돌이

calendar

1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

Notice

2019. 10. 4. 09:39 델파이

// IPHLPAPI.DLL 의 Delphi 헤더파일은 JEDI 에서 받을 수 있습니다
//   ftp://delphi-jedi.org/api/IPHlpAPI.zip

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Winsock, IpHlpApi, IPTypes, IpIfConst;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function GetAdaterTypeName(Type_:Uint):string;
begin
  case Type_ of
    MIB_IF_TYPE_ETHERNET: begin
      result:='Ethernet adapter';
    end;
    MIB_IF_TYPE_TOKENRING: begin
      result:='oken Ring adapter';
    end;
    MIB_IF_TYPE_FDDI: begin
      result:='FDDI adapter';
    end;
    MIB_IF_TYPE_PPP: begin
      result:='PPP adapter';
    end;
    MIB_IF_TYPE_LOOPBACK: begin
      result:='Loopback adapter';
    end;
    MIB_IF_TYPE_SLIP: begin
      result:='Slip adapter';
    end;
    else begin
      result:='Unknow Adapter type';
    end;
  end;
end;

function GetNodeTypeName(Type_:Uint):string;
begin
  case Type_ of
    1: result:='Broadcast';
    2: result:='Peer to peer';
    4: result:='Mixed';
    8: result:='Hybrid';
    else begin
      result:='Unknown';
    end;
  end;
end;

function Formatmac(pAdapt:PIP_ADAPTER_INFO):string;
var
  i:Integer;
begin
  result:='';
  for i:=0 to pAdapt^.AddressLength-1 do begin
    if (i = (pAdapt^.AddressLength - 1)) then begin
      result:=result+Format('%.2X', [Integer(pAdapt^.Address[i])]);
    end else begin
      result:=result+Format('%.2X-', [Integer(pAdapt^.Address[i])]);
    end;
  end;
end;


function B2S(b:Boolean):String;
begin
  if b then result:='Yes' else result:='No';
end;

Procedure IPConfig(Target:TStrings);
var
  Err:DWORD;
  pFixedInfo:PFIXED_INFO;
  FixedInfoSize:DWORD;
  pAdapterInfo, pAdapt:PIP_ADAPTER_INFO ;
  AdapterInfoSize:DWORD;
  pAddrStr:PIP_ADDR_STRING;
begin
  // Get the main IP configuration information for this machine using a FIXED_INFO structure
  Err := GetNetworkParams(NIL, FixedInfoSize);
  if (Err <> 0) then begin
    if (Err <> ERROR_BUFFER_OVERFLOW) then begin
      raise Exception.CreateFmt(
        'GetNetworkParams sizing failed with error %d',
        [Err]
      );
    end;
  end;

  // Allocate memory from sizing information
  pFixedInfo := PFIXED_INFO(GlobalAlloc(GPTR, FixedInfoSize));
  if not Assigned(pFixedInfo) then begin
    raise Exception.Create(
      'Memory allocation error'
    );
  end;

  Err := GetNetworkParams(pFixedInfo, FixedInfoSize);
  if (Err = 0) then begin
    Target.Add(Format('Host Name . . . . . . . . . : %s', [pFixedInfo^.HostName]));
    Target.Add(Format('DNS Servers . . . . . . . . : %s', [pFixedInfo^.DnsServerList.IpAddress.S]));
    pAddrStr := pFixedInfo^.DnsServerList.Next;
    while (pAddrStr<>NIL) do begin
      Target.Add(Format('%s', [pAddrStr^.IpAddress.S]));
      pAddrStr := pAddrStr^.Next;
    end;

    Target.Add('Node Type . . . . . . . . . : '+GetNodeTypeName(pFixedInfo^.NodeType));

    // if you really need it....
    //    printf("\tNetBIOS Scope ID. . . . . . : %s\n", pFixedInfo->ScopeId);
    //    printf("\tIP Routing Enabled. . . . . : %s\n", (pFixedInfo->EnableRouting ? "yes" : "no"));
    //    printf("\tWINS Proxy Enabled. . . . . : %s\n", (pFixedInfo->EnableProxy ? "yes" : "no"));
    //    printf("\tNetBIOS Resolution Uses DNS : %s\n", (pFixedInfo->EnableDns ?"yes" : "no"));
  end; // if

  //
  // Enumerate all of the adapter specific information using the IP_ADAPTER_INFO structure
  // Note:  IP_ADAPTER_INFO contains a linked list of adapter entries.
  //
  AdapterInfoSize := 0;
  Err := GetAdaptersInfo(NIL, AdapterInfoSize);
  if (Err <> 0) then begin
    if (Err <> ERROR_BUFFER_OVERFLOW) then begin
      raise Exception.CreateFmt(
        'GetAdaptersInfo sizing failed with error %d',
        [Err]
      );
    end;
  end;

  // Allocate memory from sizing information
  pAdapterInfo := PIP_ADAPTER_INFO(GlobalAlloc(GPTR, AdapterInfoSize));
  if not Assigned(pAdapterInfo) then begin
    raise Exception.Create(
      'Memory allocation error'
    );
  end;

  // Get actual adapter information
  Err := GetAdaptersInfo(pAdapterInfo, AdapterInfoSize);
  if (Err <> 0) then begin
    raise Exception.CreateFmt('GetAdaptersInfo failed with error %d',[Err]);
  end;

  pAdapt := pAdapterInfo;

  while (pAdapt<>NIL) do begin
    Target.Add(GetAdaterTypeName(pAdapt^.Type_));
    Target.Add(pAdapt^.AdapterName);
    Target.Add(Format('Description . . . . . . . . : %s',[pAdapt^.Description]));
    // mac address
    Target.Add('Physical Addresses (MAC). . . . : '+Formatmac(pAdapt));
    Target.Add('DHCP Enabled. . . . . . . . : '+B2S(pAdapt^.DhcpEnabled<>0));

    // list ip addresses
    pAddrStr := @pAdapt^.IpAddressList;
    while (pAddrStr<>NIL) do begin
      Target.Add('IP Address. . . . . . . . . : '+pAddrStr^.IpAddress.S);
      Target.Add('Subnet Mask . . . . . . . . : '+pAddrStr^.IpMask.S);
      pAddrStr := pAddrStr^.Next;
    end; // end

    // list gateways
    Target.Add('Default Gateway . . . . . . : '+pAdapt^.GatewayList.IpAddress.S);
    pAddrStr := pAdapt^.GatewayList.Next;
    while(pAddrStr <>NIL) do begin
      Target.Add(pAddrStr^.IpAddress.S);
      pAddrStr := pAddrStr^.Next;
    end; // while

    // DCHP
    Target.Add('DHCP Server . . . . . . . . : '+pAdapt^.DhcpServer.IpAddress.S);

    // WINS
    Target.Add('Primary WINS Server . . . . : '+pAdapt^.PrimaryWinsServer.IpAddress.S);
    Target.Add('Secondary WINS Server . . . : '+pAdapt^.SecondaryWinsServer.IpAddress.S);

  (*

    // if you really need it....
        struct tm *newtime;

        // Display coordinated universal time - GMT
        newtime = gmtime(&pAdapt->LeaseObtained);
        printf( "\tLease Obtained. . . . . . . : %s", asctime( newtime ) );

        newtime = gmtime(&pAdapt->LeaseExpires);
        printf( "\tLease Expires . . . . . . . : %s", asctime( newtime ) );
  *)

    // next adapter
    pAdapt := pAdapt^.Next;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  IPConfig(Memo1.Lines);
end;

end.

posted by 유돌이
2019. 10. 4. 09:39 델파이

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Winsock, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    Edit2: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  function SendARP(Destip,scrip:DWORD;pmacaddr:PDWORD;VAR phyAddrlen:DWORD):DWORD; stdcall ;external 'iphlpapi.dll' ;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function GetmacFromIP(IP: String): String;
  type
    Tinfo = array[0..7] of byte;
var
  dwTargetIP: dword;
  dwmacAddress: array[0..1] of DWORD;
  dwmacLen: DWORD;
  dwResult: DWORD;
  X: Tinfo;
  stemp:string;
  iloop:integer;
begin
  dwTargetIP := Inet_Addr(pchar(ip));
  dwmacLen := 6;
  dwResult := SendARP(dwtargetip,0,@dwmacaddress[0], dwmaclen);
  if dwResult= NO_ERROR then
  begin
    x:= tinfo(dwmacAddress);

    for iloop:= 0 to 5 do
    begin
      stemp:= stemp+inttohex(x[iloop],2);
    end;

    Result:= stemp;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  // Edit1 에 도메인 내의 IP를 입력하고 버튼을 클릭하면 mac 주소를 구해옵니다
  Edit2.Text := GetmacFromIP(Edit1.Text);
end;

end.

posted by 유돌이
2019. 10. 2. 11:39 델파이

// Call CoCreateGuid. The last six bytes are equal to the mac address of
// the Ethernet card. (Note that if you have more than one NIC in your
// computer, you'll get the mac address of one of them, but you can't
// easily control which one.)

// Sneeky... I like it! This will work quite neatly on systems without an
// ethernet card as well. AFAIK this part of the GUID is constant even if you
// only have PPP or even no-networking installed. A useful source of machine
// unique IDs...makes you wonder what the fuss about the PIII ID was about(not
// that I think it's a good idea ;)

// Tip: 델파이 IDE에서 Ctrl-Shift-G 를 눌러보세요...
// GUID가 생성 되는데 뒤에 6바이트(2자리씩 12글자) 는 네트워크 환경이
// 있다면 mac-address 와 같습니다
// PPP or even no-networking

function GetNicAddr: AnsiString;
const
  GUID_MAX = 72;
var
  guid: TGuid;
  buf: array[0..GUID_MAX] of WideChar;
begin
  CoCreateGuid(@guid);
  StringFromGUID2(guid, buf, GUID_MAX);
  Result := Copy(WideCharToString(buf),26,12);
end;

posted by 유돌이
2019. 10. 2. 11:39 델파이

타입

범위

형식

Integer

-2147483648 ~ 2147483647

부호를 가진 32bits (4 Bytes)

Cardinal

0 ~ 4294967295

부호 없는 32bits (4 Bytes)

  <?XML:NAMESPACE PREFIX = O />

 

 

ShortInt

-128 ~ 127

부호를 가진 8bits (1 Byte)

Byte

0 ~ 255

부호 없는 8bits (1 Byte)

SmallInt

-32768 ~ 32767

부호를 가진 16bits (2 Bytes)

Word

0 ~ 65535

부호 없는 16bits (2 Bytes)

LongInt

-2147483648 ~ 2147483647

부호를 가진 32bits (4 Bytes)

LongWord

0 ~ 4294967295

부호 없는 32bits (4 Bytes)

Int64

-263 ~ 263-1

(-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807)

부호를 가진 64bits (8 Bytes)

Uint64

0 ~ 264-1

(0 ~ 18,446,744,073,709,551,615)

부호 없는 64bits (8 Bytes)

 

출차 : http://hook.tistory.com/153 

posted by 유돌이
2019. 10. 2. 11:38 델파이

procedure SetHighPriority(ProcName: String);
var
  Process32: TProcessEntry32;
  H: THandle;
  Next: Boolean;
  pID: DWORD;


begin
  Process32.dwSize:=SizeOf(Process32);
  H:=CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);

 

  if Process32First(H, Process32) then begin
    repeat
      Next:=Process32Next(H, Process32);
      if Process32.szExeFile=ProcName then begin
        pID:=OpenProcess(PROCESS_ALL_ACCESS, False, Process32.th32ProcessID);
        if pID<>0 then begin
          ShowMessage('Success: '+ProcName);
          SetPriorityClass(pID, HIGH_PRIORITY_CLASS);
        end
        else ShowMessage('Error : OpenProcess');
      end;
    until not Next;
  end;

 

  CloseHandle(pID);

  CloseHandle(H);
end;

posted by 유돌이
2019. 10. 1. 16:19 델파이

델파이로 만든 실행파일이 자꾸 바이러스에 감염되었다고 한다.

 

검색하니 역시나 델파이4~7 만 걸리는 바이러스로 악성코드와 바이러스 둘다 걸리는 특이한 놈이라고 한다

 

다음은 현승현 님이 작성한 글을 퍼왔다

  

1. HKLM\Software\Borland\Delphi(4 ~ 7) 의 RootDir 키를 참조하여 델파이의 루트 경로를 구합니다.

2. 1. 에서 구한 경로를 기준으로 \source\rtl\sys\SysConst.pas 파일을 \lib\sysconst.pas 파일로 복사하면서...

소스파일 중간에 바이러스 코드를 집어넣습니다.

3. \lib 폴더의 기존의 SysConst.dcu 파일을 SysConst.bak 파일로 백업합니다.

4. dcc32.exe 이용하여 바이러스 코드가 심어진 sysconst.pas 를 새로 컴파일합니다. (새로운 SysConst.dcu 생성)

5. 새로운 SysConst.dcu 가 생성이 되면 감염된 소스코드 SysConst.pas 파일을 삭제합니다.

이후에 델파이에서 컴파일되는 실행파일들은 모두 바이러스 코드가 심어진 SysConst.dcu 가 적용되면서..

해당 실행파일에 바이러스 코드가 추가되는 방식입니다.

<< 복구방법 >>

델파이 라이브러리를 복구하기 위해서는 \lib 폴더의 SysConst.dcu 파일을 제거 후, SysConst.bak 파일을

SysConst.dcu 파일로 이름을 변경해주거나, \source\rtl\sys 폴더의 SysConst.pas 파일을 새로 컴파일해서...

해당 SysConst.dcu 파일을 덮어쓰면 됩니다.

이게 복잡하다 싶으시면, 델파이 삭제 후~ 재설치하는 방법도 있습니다 :D

감염된 파일 복구 방법은 아직 조금 더 봐야겠지만..

카스퍼스키의 경우, 해당 바이러스 코드 영역(대략 4080 바이트 정도)을 '00' 으로 덮어쓴 후,

바이러스 코드 영역을 호출하는 CALL 명령을 NOP(90) 으로 치환하는 방식이었습니다.

 

다행히 업체서버가 카스퍼스키라 아무 이상이 없는것 같다. 그러고보니 한번씩 랜덤하게 메모리 에러 나는것도 이놈때문이라 생각된다...현재는... 

posted by 유돌이
2019. 10. 1. 16:17 델파이

Sometimes the simple things are harder than you expected and dbexpress probably comes under that category, it was less express than I had expected but once you figure things out it does work. Some of the problems were my fault while others took time due to the obscur nature of the errors returned by XE and XE2.

If you start by adding the TSQLConnect component, select the MySQL driver and configure your HostName, Database, UserName and Password you can try and connect, you will most likely strike the following error :-

 

Show Plain Text

 

Text code

  1. DBX Error: Driver could not be properly initialized. Client library may be missing, not installed properly, of the wrong version, or the driver maybe be missing from the system path...

So once you figure out that your missing the libmysql.dll you might try and grab the latest MYSQL C Connector from dev.mysql.com, they are up to version 6.0.2 at the time of writing this, you'll get the same error above. I was getting a more obscure crash before XE2 Update 1 which I didn't note down at the time, that abstract error message took me a while to figure out and was related to the libmysql.dll version.

It would be nice if embarcadero provided a location where you could download the compatible libmysql.dll files that work with dbexpress, it is worth noting that the XE2 read me does come with the following note :-

Show Plain Text

 

Text code

  1. Supported Servers

  2. dbExpress

  3. ...

  4. MySQL 5.1, 5.0.27, 4.1* (Pro/Ent/Ult/Arch) (Driver dbxMYS.dll, Client libmysql.dll)

  5.  

  6. The following combinations have been tested:

  7. LibMySQL.dll (5.1.XX)  DBXMys.dll  MySQL 4.0.XX Server  

  8. LibMySQL.dll (5.1.XX)  DBXMys.dll  MySQL 4.0.XX Server  

  9. LibMySQL.dll (5.1.XX)  DBXMys.dll  MySQL 5.0.XX Server  

  10. LibMySQL.dll (5.1.XX)  DBXMys.dll  MySQL 5.1.XX Server

 

To get a 5.1.XX compatible DLL you will need to download an achieved mysql complete installation zip and extract the DLL as no compatible versioned MYSQL C Connector package could be downloaded when I looked.

To save you some time I added zip download containing the win32 x86 libmysql.dll for those who wish to download.

This is libmysql.dll version 5.1.59 win32 x86 DLL which I have tested and works with both XE and XE2.

posted by 유돌이
2019. 9. 30. 11:51 델파이

function ChangeFileExt(const FileName, Extension: string): string; 
// 바뀐 문자열만 리턴
// aaa.txt 를 aaa.avi 로 바꿀 경우
// ShowMessage( ChangeFileExt('aaa.txt', '.avi') );
// aaa.avi 로 출력

function FileSize(var F): Integer; 
// 파일 크기

function FileAge(const FileName: string): Integer; 
// 파일을 생성한 날짜

function FileDateToDateTime(FileDate: Integer): TDateTime; 
// 날짜 := FileDateToDateTime( FileAge('FileName') );

function FileSetDate(Handle: Integer; Age: Integer): Integer; overload; 
// 파일을 생성 날짜 변경 

function DateTimeToFileDate(DateTime: TDateTime): Integer; 
// TDateTime형을 Integer형으로 리턴

function FileSetAttr(const FileName: string; Attr: Integer): Integer; 
// 파일의 속성 변경(읽기전용,숨김등..) 

function FileSetReadOnly(const FileName: string; ReadOnly: Boolean): Boolean; 
// True=읽기전용, False=해제 

function DiskSize(Drive: Byte): Int64; 
// 드라이브(디스크) 용량

function DiskFree(Drive: Byte): Int64; 
// 드라이브 남은 용량 
// (Drive: 0=Default Drive, 1=A:, 2=B:, 3=C:, 4=D: 등) 

function AnsiExtractQuotedStr(var Src: PChar; Quote: Char): string; 
function AnsiDequotedStr(const S: string; AQuote: Char): string; 
// ShowMessage( AnsiDequotedStr('-ABCDEF-GHIJK$..', '-') ); 
// Result -> ABCDEF 

function AnsiLastChar(const S: string): PChar; 
// 문자열의 마지막 문자 리턴 (2Byte 문자도 가능)

procedure AppendStr(var Dest: string; const S: string); deprecated; 
// Dest := Dest + S;

function BoolToStr(B: Boolean; UseBoolStrs: Boolean = False): string; 
// Boolean 값 비교, UseBoolStrs 을 True로 할 경우 문자열로 리턴 

function ByteToCharIndex(const S: string; Index: Integer): Integer; 
// S 문자열 길이를 리턴. S 문자열 길이보다 Index 값이 크면 0을 리턴한다. (그외 Index 값 리턴) 

function ByteToCharLen(const S: string; MaxLen: Integer): Integer; 
// S 문자열 길이보다 MaxLen 값이 크면, S 길이를 리턴한다. (그 외 MaxLen 값 리턴) 

function ByteType(const S: string; Index: Integer): TMbcsByteType; 
// S[Index] 값이 1바이트 값인지, 2바이트(한글) 값의 첫번째 바이트인지, 두번째 바이트인지 판별한다. 

ex) 
var 
 ty: TMbcsByteType; 
begin 
 ty := ByteType('ABC하하012',5); 
 case ty of 
   mbSingleByte: ShowMessage('1byte 문자'); 
   mbLeadByte  : ShowMessage('2byte 문자의 첫번째 바이트'); 
   mbTrailByte : ShowMessage('2byte 문자의 두번째 바이트') 
 end; 
end; 

posted by 유돌이
2019. 9. 30. 11:50 델파이

procedure ForceDeleteDirContent(dir: string);
var i: integer;
sDirectory: string;
sr: TSearchRec;
beginsDirectory := IncludeTrailingPathDelimiter( dir );
i := FindFirst( sDirectory+’*.*’,faAnyFile,sr );
while i = 0 do begin
if ( sr.Attr and faDirectory ) = faDirectory then
DeleteDirectory( sDirectory+sr.Name )
else begin

if not DeleteFile( sDirectory+sr.Name ) then begin
FileSetAttr (sDirectory+sr.Name, 0); { reset all flags }
DeleteFile (sDirectory+sr.Name);
end;

end;
i := FindNext( sr );
end;
FindClose( sr );
end;

'델파이' 카테고리의 다른 글

[델파이] DBX error.. 해결 방법  (0) 2019.10.01
[델파이] sysutils.pas 의 유용한 함수  (0) 2019.09.30
시스템 제어관련 정보  (0) 2019.09.30
시스템 종료함수  (0) 2019.09.27
OS버전 체크  (0) 2019.09.27
posted by 유돌이
2019. 9. 30. 11:50 델파이

시스템종료 메소드는 ExitWindowsEx(EWX_SHUTDOWN,0);

시스템재시작 메소드는 ExitWindowsEx(EWX_REBOOT,0);

시스템강제종료 메소드는 ExitWindowsEx(EWX_FORCE, 0);

시스템 LOG OFF 메소드는 ExitWindowsEx(EWX_LOGOFF, 0);

시스템 PowerOff 메소드는 ExitWindowsEx(EWX_POWEROFF,0);

'델파이' 카테고리의 다른 글

[델파이] sysutils.pas 의 유용한 함수  (0) 2019.09.30
delphi ForceDeleteDirContent();  (0) 2019.09.30
시스템 종료함수  (0) 2019.09.27
OS버전 체크  (0) 2019.09.27
메모리 사용정보  (0) 2019.09.27
posted by 유돌이