server2.c
#include <sys/socket.h>/* socket, connect, bind, listen, AF_INET, SOCK_STREAM */
#include <stdio.h> /* printf, perror */
#include <unistd.h> /* read, write, close, STDIN_FILENO */
#include <arpa/inet.h> /* htons, sockaddr_in, INADDR_ANY */
#include "socktest2.h" /* shared defines */
/* How many pending connections we'll allow */
#define BACKLOG 5
int main(void)
{
int sfd; /* server file descriptor */
int cfd; /* client file descriptor */
ssize_t bytes_read; /* count of bytes read from socket */
char buffer[BUF_SIZE]; /* to transfer data in the socket */
struct sockaddr_in addr = {0}; /* address for connecting */
/* Create the server socket */
sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd == -1)
{
perror("socket");
return 1;
}
/* Set the domain type (Internet) */
addr.sin_family = AF_INET; /* Internet Protocol v4 */
addr.sin_addr.s_addr = INADDR_ANY; /* Any address on this computer */
addr.sin_port = htons(PORT_NUMBER); /* Port (arbitrary 12345) */
/* Bind the socket to the IP address */
if (bind(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) == -1)
{
perror("bind");
return 2;
}
/* Indicate that the socket is ready (listening) for a connection */
if (listen(sfd, BACKLOG) == -1)
{
perror("listen");
return 3;
}
/* Process incoming connections forever */
for (;;)
{
/* sleep(5); */ /* Test BACKLOG values */
/*
* Accept the next incoming connection. It returns the socket
* descriptor from the client that is connecting in case we want
* to send data back.
*/
cfd = accept(sfd, NULL, NULL);
if (cfd == -1)
{
perror("accept");
return 4;
}
/* Read from client socket until EOF (in BUF_SIZE chunks) */
while ((bytes_read = read(cfd, buffer, BUF_SIZE)) > 0)
{
/* Write bytes to stdout */
if (write(STDOUT_FILENO, buffer, bytes_read) != bytes_read)
{
printf("write failed\n");
return 5;
}
}
/* Check if the read had an error */
if (bytes_read == -1)
{
perror("read");
return 6;
}
/* Close client file descriptor */
if (close(cfd) == -1)
{
perror("close");
return 7;
}
}
/* Close server file descriptor */
if (close(sfd) == -1)
{
perror("close");
return 8;
}
return 0;
}