Client program:
Returns the current time and date through the server.
#include "Unp.h"
#include "My_err.h"
int main (int argc, char** argv)
{
int SOCKFD, n;
Char Recvline[maxline + 1];
struct sockaddr_in servaddr;
if (argc! = 2)
Err_quit ("usage:a.out<ipaddress>");
if ((SOCKFD = socket (af_inet, sock_stream, 0)) < 0)
Err_sys ("socket error");
Bzero (&servaddr, sizeof (SERVADDR));
servaddr.sin_family = af_inet;
Servaddr.sin_port = htons (13);
if (Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <= 0)
Err_quit ("Inet_pton error for%s", argv[1]);
if (Connect (SOCKFD, (sa*) &servaddr, sizeof (SERVADDR)) < 0)
Err_sys ("Connect error");
while ((n = Read (SOCKFD, Recvline, MAXLINE)) > 0)
{
Recvline[n] = 0;
if (fputs (recvline, stdout) = = EOF)
Err_sys ("fputs error");
Server-side programs:
Obtain the IP and port number of the client side. Inet_ntop converts the 32-bit IP address in the socket address structure to a dotted-decimal ASCII string, calling Nthos to convert the 16-bit port number from the network byte order to the host byte order.
int main (int argc, char** argv)
{
int LISTENFD, CONNFD;
Socklen_t Len;
struct sockaddr_in servaddr, cliaddr;
Char Buff[maxline];
teme_t ticks;
LISTENFD = socket (af_inet, sock_stream, 0);
Bzero (&servaddr, sizeof (SERVADDR));
servaddr.sin_family = af_inet;
SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
Servaddr.sin_port = htons (13);
Bind (LISTENFD, (sa*) &servaddr, sizeof (SERVADDR));
Listen (LISTENFD, Listenq);
for (;;)
{
len = sizeof (CLIADDR);
CONNFD = Accept (LISTENFD, (sa*) &cliaddr, &len);
printf ("Connection from%s,port%d \ n", Inet_ntop (af_inet, &cliaddr.sin_addr, buff, sizeof (buff)), Ntohs ( Cliaddr.sin_port));
Ticks = time (NULL);
snprintf (buff, sizeof), "%.24s\r\n", CTime (&ticks));
Crite (CONNFD, Buff, strlen (buff));
Close (CONNFD);
}
}
Client-server program for sockets