unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,Winsock, StdCtrls;//加入Winsock单元
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
Ip:string;//存放分段ip
IpStr:String;//存放最终IP
Buffer:Array[1..32] of Char;//存放主机名的缓冲区
i:integer;
WSData:TWSAData;//为了调入Ws2_32.dll初始化windows用
Host
HostEnt;//指向ThostEnt类的指针
begin
if WSAstartup(2,WSData)<>0 then //为程序使用WS2_32.DLL初始化
//初始化失败则退出
begin
ShowMessage('失败');
halt;
end;
try
if GetHostName(@Buffer[1],32)<>0 then
//调用函数失败则退出
begin
ShowMessage('没有找到主机名称');
halt;
end;
except
ShowMessage('没有成功返回主机名称');
halt;
end;
Host:=GetHostName (@Buffer[1]);
if Host=nil then
begin
ShowMessage('ip地址为空');
halt;
end
else
//初始化,函数调用成功则开始读取IP
begin
Edit2.Text:=Host.h_name;
Edit3.text:=Chr(Host.h_addrtype+64);
//将地址类型的由数字转换对应大写字母IP地址的4个部分
for i:=1 to 4 do
begin
ip:=IntToStr(ord(host.h_addr^[i-1]));
ShowMessage('分段IP为:'+Ip);
ipStr:=Ipstr+ip;
if i<4 then
ipstr:=ipstr+'.'
else
Edit1.text:=IpStr;
end;
end;
WSACleanup;//扫尾工作
end;