{This is a TCP server using PMWsock}
program TCPServer;
uses
Winsock, SysUtils;
const
SERVER_PORT = 1234; {Arbitrary port number}
MAX_CLIENTS = 10; {Maximum number of concurrent clients}
var
WSAData: TWSAData;
ServerSocket, ClientSocket: TSocket;
ServerAddr, ClientAddr: TSockAddr;
CommAddr : SockAddr;
Buffer: array[0..255] of Char;
BytesSent, BytesRecv: Integer;
Message: String;
ClientAddrSize: Integer;
CommAddrSize : LongInt;
CommLen: LONGINT;
i : integer;
output :string;
begin
{Initialize Winsock}
WSAStartup($0101, WSAData);
{Create a socket}
ServerSocket := socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
{Bind the socket to a port}
ServerAddr.sin_family := AF_INET;
ServerAddr.sin_port := htons(SERVER_PORT);
ServerAddr.sin_addr.S_addr := INADDR_ANY;
bind(ServerSocket, ServerAddr, SizeOf(ServerAddr));
{Listen for incoming connections}
listen(ServerSocket, MAX_CLIENTS);
WriteLn('Server is listening on port ', SERVER_PORT);
{Accept a connection from a client}
ClientAddrSize := SizeOf(ClientAddr);
ClientSocket := accept(ServerSocket, @ClientAddr, @ClientAddrSize);
WriteLn('Accepted a connection from ', inet_ntoa(ClientAddr.sin_addr));
CommLen := Sizeof(CommAddr);
Writeln('ERROR: ', getpeername(ClientSocket, CommAddr,CommLen));
Writeln('Server Socket: ',ServerSocket);
Writeln('Client Socket: ',ClientSocket);
writeln('Last Error: ', WSAGetLastError);
Writeln('Connected IP: ');
For i := 0 to 13 do
BEGIN
write(commaddr.sa_data[i]); write(' ');
END;
Writeln;
Writeln('sa_family: ',commaddr.sa_family);
Writeln(strpas(inet_ntoa(PSockAddrIn(@CommAddr.sa_data)^.sin_addr)));
{Receive a message from the client}
BytesRecv := recv(ClientSocket, Buffer, SizeOf(Buffer), 0);
Buffer[BytesRecv] := #0;
WriteLn('Received: ', Buffer);
{Send a message to the client}
Message := 'Hello, this is a TCP server';
{BytesSent := send(ClientSocket, Message[1], Length(Message), 0);}
{Close the client socket}
closesocket(ClientSocket);
{Close the server socket}
closesocket(ServerSocket);
{Clean up Winsock}
WSACleanup;
end.