3

如何sockaddr_in从套接字句柄获取关联,以便从中获取端口和地址?或者还有其他关于如何从 SocketHandle 获取 IP 和端口的信息吗?

例如:

function GetSocketPort ( s : TSocket ) : Integer;
var
  Addr                  : sockaddr_in;
begin
  // Get sockaddr_in from a socket
end;

function GetSocketAddress ( s : TSocket ) : String;
var
  Addr                  : sockaddr_in;
begin
  // Get sockaddr_in from a socket
end;

function ConnectToHost (Host : pchar; Port : Integer) : TSocket;
var
  Addr                  : sockaddr_in;
begin
  Addr.sin_family       := AF_INET;
  Addr.sin_port         := htons(Port);
  result                := Socket(AF_INET, 1, 6);
  Addr.sin_addr.S_addr  := INET_ADDR(Host);
  if not( (Connect(result, Addr, SizeOf(Addr)) = 0) ) then result := 0;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  MySocket : TSocket;
begin
  MySocket := ConnectToHost ('127.0.0.1', 8080);
  if MySocket <> 0 then begin
    // GetSocketAddress (MySocket);
    // GetSocketPort (MySocket);
  end;
end;
4

1 回答 1

7

您可以像这样使用getsockname本地端口和地址的功能以及getpeername远程端口的功能

function GetLocalSocketPort ( s : TSocket ) : Integer;
var
  Addr                  : TSockAddrIn;
  Size: integer;
begin
  Size := sizeof(Addr);
  getsockname(s, Addr, Size);
  Result := ntohs(Addr.sin_port);
end;

function GetLocalSocketAddress ( s : TSocket ) : String;
var
  Addr                  : TSockAddrIn;
  Size: integer;
begin
  Size := sizeof(Addr);
  getsockname(s, Addr, Size);
  Result := inet_ntoa(Addr.sin_addr);
end;


function GetRemoteSocketPort ( s : TSocket ) : Integer;
var
  Addr                  : TSockAddrIn;
  Size: integer;
begin
  Size := sizeof(Addr);
  getpeername(s, Addr, Size);
  Result := ntohs(Addr.sin_port);
end;

function GetRemoteSocketAddress ( s : TSocket ) : String;
var
  Addr                  : TSockAddrIn;
  Size: integer;
begin
  Size := sizeof(Addr);
  getpeername(s, Addr, Size);
  Result := inet_ntoa(Addr.sin_addr);
end;
于 2013-07-24T23:44:03.570 回答