fpconnect¶
Open a connection to a server socket.
Declaration¶
Source position: socketsh.inc line 171
function fpconnect(s: cint; name: psockaddr; namelen: TSockLen) : cint;
Description¶
fpConnect uses the socket s to open a connection to a peer, whose address is described by Name. NameLen contains the length of the address. The type of Name depends on the kind of connection you are trying to make, but is generally one of TSockAddr or TUnixSockAddr.
The fpConnect function returns zero if the call was success full, -1 in case of error.
Errors¶
On error, -1 is returned and errors are reported in SocketError.
See also¶
| Name | Description |
|---|---|
| fpListen | Listen for connections on a socket. |
| fpBind | Bind a socket to an address. |
| fpAccept | Accept a connection from a socket. |
Example¶
Program Client;
{
Program to test Sockets unit by Michael van Canneyt and Peter Vreman
Client Version, First Run sock_svr to let it create a socket and then
sock_cli to connect to that socket
}
{$mode objfpc}
{$h+}
uses Sockets;
procedure PError(const S : string);
begin
writeln(S,SocketError);
halt(100);
end;
Var
SAddr : TInetSockAddr;
Buffer : string;
fd,err : Longint;
i : integer;
procedure send(const msg : string);
begin
fpSend(fd,@msg[1],length(msg),0);
end;
function Receive(var S : string) : boolean;
var
nRead : integer;
begin
SetLength(S,255);
nRead:=fpRecv(fd,@S[1],255,0);
Result:=nRead>0;
if Result then
SetLength(S,nRead)
else
SetLength(S,0);
end;
begin
fd:=fpSocket (AF_INET,SOCK_STREAM,0);
if fd=-1 then
Perror('Client : Socket : ');
SAddr.sin_family:=AF_INET;
{ port 50000 in network order }
SAddr.sin_port:=htons(5000);
{ localhost : 127.0.0.1 in network order }
SAddr.sin_addr.s_addr:=HostToNet((127 shl 24) or 1);
err:=fpConnect(fd,@SAddr,Sizeof(SAddr));
if err=-1 then
PError('Client : Connect : ')
else
begin
if Receive(Buffer) then
WriteLn(Buffer);
Buffer:='This is a textstring sent by the Client.';
Send(Buffer);
end;
CloseSocket(fd);
end.
Example¶
program pfinger;
uses sockets,errors;
Var
Addr : TInetSockAddr;
S : Longint;
Sin,Sout : Text;
Line : string;
begin
Addr.sin_family:=AF_INET;
{ port 79 in network order }
Addr.sin_port:=79 shl 8;
{ localhost : 127.0.0.1 in network order }
Addr.sin_addr.s_addr:=((1 shl 24) or 127);
S:=fpSocket(AF_INET,SOCK_STREAM,0);
If Not Connect (S,ADDR,SIN,SOUT) Then
begin
Writeln ('Couldn''t connect to localhost');
Writeln ('Socket error : ',strerror(SocketError));
halt(1);
end;
rewrite (sout);
reset(sin);
writeln (sout,paramstr(1));
flush(sout);
while not eof(sin) do
begin
readln (Sin,line);
writeln (line);
end;
fpShutdown(s,2);
close (sin);
close (sout);
end.