1
edit
Changes
no edit summary
* make
* make release
Feb 8, 2009:
*yum install seamonkey //used to edit html to get the C program
*yum groupinstall "Development Libraries"
*yum groupinstall "Development Tools"
*server.c
#include <error.h>
#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/poll.h>
#include <sys/poll.h>
int main (int argc, char *argv[])
{
struct servent *s = getservbyname ("echo", "tcp");
if (s == NULL)
error (EXIT_FAILURE, errno, "getservent");
struct pollfd fds[1];
int nfds = 0;
fds[nfds].fd = socket (AF_INET, SOCK_STREAM, 0);
if (fds[nfds].fd == -1)
error (EXIT_FAILURE, errno, "socket");
fds[nfds].events = POLLIN;
int opt = 1;
setsockopt (fds[nfds].fd, SOL_SOCKET, SO_REUSEADDR,
opt, sizeof (opt));
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = s->s_port;
sin.sin_addr.s_addr = INADDR_ANY;
if (bind (fds[nfds].fd,
&sin, sizeof (sin)) != 0)
error (EXIT_FAILURE, errno, "bind");
if (listen (fds[nfds].fd, SOMAXCONN) != 0)
error (EXIT_FAILURE, errno, "listen");
++nfds;
int i = 0;
while (1)
{
int n = poll (fds, nfds, -1);
if (n > 0)
if (fds[i].revents & POLLIN)
{
struct sockaddr_in rem;
socklen_t remlen = sizeof (rem);
int fd = accept (fds[i].fd, (struct sockaddr *) &rem, &remlen);
if (fd != -1)
{
struct hostent *h = gethostbyaddr (&rem.sin_addr,
sizeof (rem.sin_addr),
rem.sin_family);
char *buf1 = h ? h->h_name : "???";
char *buf2 = inet_ntoa (rem.sin_addr);
printf ("connection from %s (%s)\n", buf1, buf2);
char buf[1000];
ssize_t l = read (fd, buf, sizeof (buf));
buf[0]='J';
write (fd, buf, l);
close (fd);
}
}
}
}
*cc server.c -o server
*client.c
#include <errno.h>
#include <error.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main (int argc, char *argv[])
{
int result = 0;
struct hostent *h = gethostbyname (argv[1]);
if (h == NULL)
error (EXIT_FAILURE, errno, "gethostbyname");
struct servent *s = getservbyname ("echo", "tcp");
if (s == NULL)
error (EXIT_FAILURE, errno, "getservbyname");
struct in_addr **addrs = (struct in_addr **) h->h_addr_list;
while (*addrs != NULL)
{
int sock = socket (PF_INET, SOCK_STREAM, 0);
if (sock != -1)
{
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = s->s_port;
sin.sin_addr = **addrs;
if (connect (sock,
(struct sockaddr *) &sin, sizeof (sin)) == 0)
{
char *line = NULL;
size_t len = 0;
ssize_t n = getline (&line, &len, stdin);
write (sock, line, n);
n = read (sock, line, len);
write (STDOUT_FILENO, line, n);
close (sock);
goto out;
}
close (sock);
}
++addrs;
}
error (0, 0, "cannot contact %s", argv[1]);
result = 1;
out:
return result;
}
*cc client.c -o client
*./server
*./client localhost //open another terminal to run it, then type a little word to test. OK