4P14
Lab 2
Sockets
In this lab we will be looking at making multiple connections to a
single server interface. Your goal in this lab will be to modify
the client and server as appropriate so multiple clients can carry
on concurrent conversations with a single server. You will need to
install telnet if it is not already installed. Try the following:
telnet localhost 80
If you get something like >telnet: command not found<
then you must install it.
Installation can be accomplished with:
yum install telnet -y
Try to telnet once again to confirm installation.
Your Lab instructor will now give you a crash course on Socket
communications. Important information should be jotted down on the
accompanying handout.
1) Download and compile
Multi_Socket.c example form the courses examples. Open a telnet
session and telnet into the server from several clients
concurrently. What did you see?
2) Consider the ability to echo back
a conversation with a client. This we accomplished in lab 1. The
server currently does the echo as part of its default response to
the client. For the most part the clients you created in Lab 1
should be almost complete and be able to carry on a conversion
with the server. Try this and show your lab leader it work.
3) On the server side, it would be
nice to see which client requested an echo back. Thus, modify the
server code to print out, which client requested a new connect and
also every time an echo request was received (as part of the
default behaviour from part 2). To do this you can use the
getpeername() system call. An example of its usage is given
below. Try to connect to other lab servers, and have them
connect to your. Be sure to disable the firewall to allow
connections. Show your lab leader it works and enjoy your 4%.
In this example,
getpeername
returns the
port and address of the
peer program.
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
f()
{
int s;
struct sockaddr_in peer;
int peer_len;
.
.
.
/* We must put the length in a variable. */
peer_len = sizeof(peer);
/* Ask getpeername to fill in peer's socket address. */
if (getpeername(s, &peer, &peer_len) == -1) {
perror("getpeername() failed");
return -1;
}
/* Print it. The IP address is often zero because */
/* sockets are seldom bound to a specific local */
/* interface. */
printf("Peer's IP address is: %s\n", inet_ntoa(peer.sin_addr));
printf("Peer's port is: %d\n", (int) ntohs(peer.sin_port));
.
.
.
}