Network Programming Snippets
Part 1 - Use TTcpServer and TTcpClient to exchange messages
Snippet to read and return your current IP address
Function GetIPAddress():String;
type
pu_long = ^u_long;
var
varTWSAData : TWSAData;
varPHostEnt : PHostEnt;
varTInAddr : TInAddr;
namebuf : Array[0..255] of ansichar;
begin
If WSAStartup($101,varTWSAData) <> 0 Then //Windows sockets data
Result := 'No. IP Address'
Else Begin
gethostname(namebuf,sizeof(namebuf)); //Local Host name
varPHostEnt := gethostbyname(namebuf); //Structure returned by Windows
varTInAddr.S_addr := u_long(pu_long(varPHostEnt^.h_addr_list^)^);
Result := inet_ntoa(varTInAddr);
End;
WSACleanup;
end;
More information about the PHostEnt structure returned by windows is here
Snippet to programmatically set Server LocalHost IP address and Port
begin
lport := inttostr(portnumber);
IPAddress := ansistring(GetIPAddress);
TCPServer1.Active := false;
TCPServer1.LocalHost := IPAddress;
TCPServer1.LocalPort := lport;
TCPServer1.Active := true;
tcpclient1.RemoteHost := IPAddress;
tcpclient1.RemotePort := lport;
label1.Caption := '>'+IPAddress+':'+lport;
end;
Receive and display server messages
procedure TForm1.TcpServer1Accept(Sender: TObject;
ClientSocket: TCustomIpClient);
begin
Memo1.Lines.add(ClientSocket.Receiveln);
end;
Send messages from the Client
begin
if TcpClient1.Connect then
begin
TcpClient1.Sendln('Message sent using port '+lport);
TcpClient1.Disconnect;
end else
begin
ShowMessage('Not connected');
end;
end;