The server

In Chapter 6, RE in Linux Platforms, we learned about using socket APIs to control network communication between a client and a server. The same code can be implemented for the Windows operating system. For Windows, the socket library needs to be initiated by using the WSAStartup API before using socket APIs. In comparison to Linux functions, instead of using writesend is used to send data back to the client. Also, regarding close, the equivalent of this is closesocket, which is used to free up the socket handle.

Here's a graphical representation of how a server and a client generally communicate with the use of socket APIs.  Take note that the functions shown in the following diagram are Windows API functions:

The socket function is used to initiate a socket connection. When we're done with the connection, the communication is closed via the closesocket function.  The server requires that we bind the program with a network port. The listen and accept function is used to  wait for client connections. The send and recv functions are used for the data transfer between the server and the client. send is used to send data while recv is used to receive data. Finally,  closesocket is used to terminate the transmission. The code below shows an actual C source code of a server-side program that accepts connections and replies with You have connected to the Genie. Nothing to see here.


int main()
{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
struct sockaddr_in ctl_addr;
int addrlen;
char sendBuff[1025];


WSADATA WSAData;

if (WSAStartup(MAKEWORD(2, 2), &WSAData) == 0)
{
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd != INVALID_SOCKET)
{
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(9999);
if (bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == 0)
{
if (listen(listenfd, SOMAXCONN) == 0)
{
printf("Genie is waiting for connections to port 9999. ");
while (1)
{
addrlen = sizeof(ctl_addr);
connfd = accept(listenfd, (struct sockaddr*)&ctl_addr, &addrlen);
if (connfd != INVALID_SOCKET)
{
printf("%s has connected. ", inet_ntoa(ctl_addr.sin_addr));

snprintf(sendBuff, sizeof(sendBuff), "You have connected to the Genie. Nothing to see here. ");
send(connfd, sendBuff, strlen(sendBuff), 0);
closesocket(connfd);
}
}
}
}
closesocket(listenfd);
}
WSACleanup();
}
return 0;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.30.253