{ 文件名:RealICQSocket.pas 功 能:此单元定义了一些Winsock应用的基本(公用)过程,函数和类型。 建 立:尹进 历 史: 2005.12.23:补文件说明信息(尹进) } unit RealICQSocket; interface uses WinSock2, SysUtils; type //Socket异常类 TSocketException = class(Exception); //IP地址类型 TIPVersion = (ipV4 = 0, ipV6 = 1); //初始化WinSock2 procedure InitWinSock2; //释放已分配的WinSock2资源 procedure FreeWinSock2; function HostToIP(Name: string; var Ip: string): Boolean; function GetHostIP(HostName: String): String; function GetLocalIP: String; implementation //------------------------------------------------------------------------------ procedure InitWinSock2; var aWSAData: TWSAData; begin if WSAStartup($202, aWSAData) <> 0 then begin raise TSocketException.Create('初始化WinSock2失败,请确认系统是否正确安装了WinSock2'); end; end; //------------------------------------------------------------------------------ procedure FreeWinSock2; begin if WSACleanup() <> 0 then begin raise TSocketException.Create('清除WinSock2资源失败,错误代码:' + IntToStr( WSAGetLastError() ) ); end; end; //------------------------------------------------------------------------------ {域名解析} function HostToIP(Name: string; var Ip: string): Boolean; var hostName : array [0..255] of char; hostEnt : PHostEnt; addr : PChar; begin gethostname (hostName, sizeof (hostName)); StrPCopy(hostName, Name); hostEnt := gethostbyname (hostName); if Assigned (hostEnt) then if Assigned (hostEnt^.h_addr_list) then begin addr := hostEnt^.h_addr_list^; if Assigned (addr) then begin IP := Format ('%d.%d.%d.%d', [byte (addr [0]), byte (addr [1]), byte (addr [2]), byte (addr [3])]); Result := True; end else Result := False; end else Result := False else begin Result := False; end; end; //------------------------------------------------------------------------------ {获取IP地址} function GetHostIP(HostName: String): String; var buf:pChar; hostent:PHostEnt; begin Result := ''; buf := Allocmem(60); strcopy(buf,PChar(HostName)); if Trim(buf)='' then gethostname(buf,60); hostent := gethostbyname(buf); Freemem(buf,60); if hostent=nil then Exit; Result := inet_ntoa(pinAddr(hostent^.h_addr^)^); end; //获取本机所有IP地址,IP地址之间用“,”隔开 function GetLocalIP: String; type TaPInAddr = Array[0..10] of PInAddr; PaPInAddr = ^TaPInAddr; var phe: PHostEnt; pptr: PaPInAddr; Buffer: Array[0..63] of Char; I: Integer; IP: String; begin IP:=''; GetHostName(Buffer, SizeOf(Buffer)); phe := GetHostByName(buffer); if phe = nil then begin Result:=IP; exit; end; pPtr := PaPInAddr(phe^.h_addr_list); I := 0; while pPtr^[I] <> nil do begin if IP = '' then IP := inet_ntoa(pptr^[I]^) else IP := IP + ',' + inet_ntoa(pptr^[I]^); Inc(I); end; Result:=IP; end; initialization InitWinSock2; finalization FreeWinSock2; end.