client2.c
#include <sys/socket.h> /* socket, connect, AF_UNIX, SOCK_STREAM */
#include <stdio.h> /* printf, perror */
#include <unistd.h> /* read, write, close, STDIN_FILENO */
#include <arpa/inet.h> /* htons, sockaddr_in, inet_addr */
#include "socktest2.h" /* shared defines */
int main(int argc, char **argv)
{
int sfd; /* socket file descriptor */
ssize_t bytes_read; /* count of bytes read from stdin */
char buffer[BUF_SIZE]; /* to transfer data in the socket */
struct sockaddr_in addr = {0}; /* address to connect to */
/* Need an IP address on the command line */
if (argc < 2)
{
printf("Usage: %s IP address\n", argv[0]);
return 5;
}
/* Create the socket (Internet domain) */
sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd == -1)
{
perror("socket");
return 1;
}
/* Set domain type */
addr.sin_family = AF_INET; /* Internet Protocol v4 */
addr.sin_addr.s_addr = inet_addr(argv[1]); /* Address given on command line */
addr.sin_port = htons(PORT_NUMBER); /* Port (arbitrary 12345) */
/* Connect socket to IP address */
if (connect(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) == -1)
{
perror("connect");
return 3;
}
/* Read from stdin until EOF (Ctrl+D) in BUF_SIZE chunks */
while ((bytes_read = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0)
{
/* Write bytes to socket */
if (write(sfd, buffer, bytes_read) != bytes_read)
{
printf("write failed\n");
return 4;
}
}
/* Check if read had an error */
if (bytes_read == -1)
{
perror("read");
return 5;
}
/* Close the socket */
close(sfd);
return 0;
}