Delphi WSAAsyncGetHostByName异步取IP地址


同步版本是GetHostByName
异步版本是WSAAsyncGetHOstByName。
它们都是由域名或者主机名返回IP地址。
如果不填写域名,解析出的是本地IP地址。

源代码:
-------------------------------------------------------------------------

unit Unit1;

interface

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

const
  WM_MYMSG=WM_USER+100;
type
  TMYMSG=record   //自定义的消息结构,也可以不用。
   msg:Word;
   wParam:Word;
   lParam:DWORD;
  end;

type
  TForm1 = class(TForm)
   Button1: TButton;
   Button2: TButton;
   Edit1: TEdit;
   Edit2: TEdit;
   Edit3: TEdit;
   Label1: TLabel;
   Label2: TLabel;
   Label3: TLabel;
   procedure Button1Click(Sender: TObject);
   procedure Button2Click(Sender: TObject);
  private
   { Private declarations }
  public
   constructor Create(AOwner: TComponent); override;
   destructor Destroy; override;
   procedure info(var msg:TMessage);message WM_MYMSG;
   { Public declarations }
  end;

var
  Form1: TForm1;
  buf:hostent;
  hwnd1:HWND;

implementation

{$R *.dfm}
{$APPTYPE CONSOLE}

constructor TForm1.Create(AOwner: TComponent);
var
  WSData:TWSAData;
begin
  inherited;
  if WSAStartup(MakeWord(2,0),WSData)<>0 then
   raise Exception.Create('winsock版本错误!');
end;

destructor TForm1.Destroy;
begin
  WSACleanup;
  inherited;
end;

procedure TForm1.Button1Click(Sender: TObject);

begin
  hwnd1:=WSAAsyncGetHostByName(Handle,WM_MYMSG,pchar(edit1.Text),
   pchar(@buf),MAXGETHOSTSTRUCT);
end;

procedure TForm1.info(var msg: TMessage); //自定义的TMYMSG 也可以
begin
  if buf.h_addr=nil then
  begin
   ShowMessage('解析失败!');
   exit;
  end;
  edit3.Text:=buf.h_name;
  edit2.Text:=format('%d.%d.%d.%d',[ord(buf.h_addr^[0]),
   ord(buf.h_addr^[1]),ord(buf.h_addr^[2]),ord(buf.h_addr^[3])]);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  WSACancelAsyncRequest(hwnd1); //中断解析
end;

end.


联系电话:
020-00000000
联系电话:
020-00000000
联系电话:
020-12345678