为什么得不到主机名?(100分)

  • 主题发起人 主题发起人 xie_huan
  • 开始时间 开始时间
X

xie_huan

Unregistered / Unconfirmed
GUEST, unregistred user!
为什么用GetHostName(),GetHostByName()得不到中文的主机名,只会得到一串
---- 的符号?请看例子:
procedure TForm1.Button1Click(Sender: TObject);
type
TaPInAddr=array[0..10] of PInAddr;
PaPInAddr=^TaPInAddr;
var
result:string;
phe:PHostEnt;
pptr:PaPInAddr;
Buffer:array[0..63] of char;
I:Integer;
GinitData:TWSADATA;
begin
WSAStartUp($101,GinitData);
result:='';
GetHostName(Buffer,SizeOf(Buffer));
phe:=GetHostByName(Buffer);
if phe=nil then exit;
pptr:=PaPInAddr(phe^.h_addr_list);
i:=0;
while pptr^<>nil do
begin
result:=StrPas(inet_ntoa(pptr^^));
inc(i);
end;
WSACleanup;
edit1.text:=result;
edit2.Text:=phe.h_name;
end;
有n个中文字符,就有2n个 - 出现
 
试试这个


// 通过调用Api函数gethostname,gethostbyname,wsastartup
//uses中加winsock
//介绍wsadata,phostent msdn
//另外gethostaddress,
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,winsock, ExtCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
StaticText1: TStaticText;
StaticText2: TStaticText;
StaticText3: TStaticText;
Panel1: TPanel;
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;
Ipstr:string;
buffer:array[1..32] of char;
i:integer;
WSData:TWSAData;
Host:PHostEnt;
begin
if WSAstartup(2,WSData)<>0 then //为程序使用WS2_32.DLL初始化
begin
showmessage('WS2_32.DLL初始化失败!');
halt;
end;
try
if gethostname(@buffer[1],32)<>0 then
begin
showmessage('没有得到主机名!');
halt;
end;

except
showmessage('没有成功返回主机名');
halt;
end;
Host:=gethostbyname(@buffer[1]);
if Host=nil then
begin
showmessage('IP地址为空!');
halt;
end
else
begin
edit2.text:=host.h_name;
edit3.text:=chr(host.h_addrtype+64);
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;
end;

end.
//WSAstartup在使用gethostname,gethostbyname前
//一定不要忘了初始化WS2_32.DLL


 
function GetComputerName:string;
var
pComputerName:PChar;
ComputerNameLen:DWORD;
begin
ComputerNameLen:=255;
GetMem(pComputerName,ComputerNameLen);
try
if not GetComputerName(pComputerName,ComputerNameLen) then
pComputerName:='没有计算机名';
ComputerName:=String(PComputerName);
finally
FreeMem(pComputerName);
End;
result:=ComputerName;
End;

 
to lanbing1400
不行,这个方法我早就试过,结果一样
 
你是什么系统?我在WIN2000下正常呀
我用的就是中文机器名
 
试试 result := WideString(StrPas(inet_ntoa(pptr^^)));
 

Similar threads

I
回复
0
查看
578
import
I
I
回复
0
查看
552
import
I
I
回复
0
查看
1K
import
I
I
回复
0
查看
836
import
I
后退
顶部