如何使用Winsock api检查互联网连接?

Davison 3 sockets delphi winsock delphi-10-seattle

我在下面构建了这个代码(基于这个例子)来检查是否存在与使用Winsockapi的互联网连接并尝试向特定网站发出GET请求(在我的情况下是google.com).

但是WSAGetLastError返回错误代码:10051.

如何修复这个?

program Project1;

uses
  Windows, SysUtils, WinSock;

function GetIPFromHostName(const HostName: string): string;
var
  WSAData: TWSAData;
  R: PHostEnt;
  A: TInAddr;
begin
  Result := '0.0.0.0';
  WSAStartup($101, WSAData);
  R := GetHostByName(PAnsiChar(AnsiString(HostName)));
  if Assigned(R) then
  begin
    A := PInAddr(R^.h_Addr_List^)^;
    Result := WinSock.inet_ntoa(A);
  end;
end;

function IsConnectedToInternet: Boolean;
var
  WSAData1: TWSAData;
  SockAddr1: TSockAddr;
  Socket1: TSocket;
begin
  Result := False;

  if WSAStartup(MAKEWORD(2, 2), WSAData1) <> 0 then
  begin
    Writeln('WinSock error');
    Exit;
  end;

  Socket1 := Socket(AF_INET, SOCK_STREAM, 0);
  if Socket1 = INVALID_SOCKET then
  begin
    Writeln('socket error');
    Exit;
  end;

  SockAddr1.sin_family := AF_INET;
  SockAddr1.sin_addr.S_addr := inet_addr(PAnsiChar(GetIPFromHostName('google.com')));
  SockAddr1.sin_port := htons(80);

  if Connect(Socket1, SockAddr1, SizeOf(SockAddr1)) <> 0 then
  begin
    Writeln('connection error #', WSAGetLastError);
    Exit;
  end;

  Result := True;

  if CloseSocket(Socket1) <> 0 then
    Writeln('error closing socket');
end;

begin
  IsConnectedToInternet;
  readln;

end.

Sertac Akyuz.. 6

编译器警告你的错误,你都尽显行in_addrsockaddr_in:

W1044对PAnsiChar的字符串的可疑类型转换

inet_addr期望ANSI字符串.您将一个unicode字符串类型转换为PAnsiChar,从而传递格式错误的字符串,导致connect无法找到目标.

更换

SockAddr1.sin_addr.S_addr := inet_addr(PAnsiChar(GetIPFromHostName('google.com')));

SockAddr1.sin_addr.S_addr :=
    inet_addr(PAnsiChar(AnsiString(GetIPFromHostName('google.com'))));


您可以使用为此目的设计的API之一,如InternetCheckConnection,或InternetGetConnectedState,或INetworkListManager界面(Vista和更高版本).

例如

const
  FLAG_ICC_FORCE_CONNECTION = 1;
begin
  if not InternetCheckConnection('http://google.com', FLAG_ICC_FORCE_CONNECTION, 0) then
    RaiseLastOSError;