如何从套接字句柄中获取关联的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;
解决方法
您可以将
getsockname
功能用于本地端口和地址,将
getpeername
用于远程端口,如此
function GetLocalSocketPort ( s : TSocket ) : Integer; var Addr : TSockAddrIn; Size: integer; begin Size := sizeof(Addr); getsockname(s,Size); Result := ntohs(Addr.sin_port); end; function GetLocalSocketAddress ( s : TSocket ) : String; var Addr : TSockAddrIn; Size: integer; begin Size := sizeof(Addr); getsockname(s,Size); Result := inet_ntoa(Addr.sin_addr); end; function GetRemoteSocketPort ( s : TSocket ) : Integer; var Addr : TSockAddrIn; Size: integer; begin Size := sizeof(Addr); getpeername(s,Size); Result := ntohs(Addr.sin_port); end; function GetRemoteSocketAddress ( s : TSocket ) : String; var Addr : TSockAddrIn; Size: integer; begin Size := sizeof(Addr); getpeername(s,Size); Result := inet_ntoa(Addr.sin_addr); end;