All of the network applications we've studied have been based on the client-server paradigm. Today, we'll investigate a network application in which all the participants are peers, with no designated "master" server.
The network application is a version of "chat". You'll write a program that accepts keyboard input, and sends the input to all other participants. Your program will also accept messages from other copies of the program, and display those messages on standard output.
Each message will consist of a character string (length determined by the length of the received message). The messages will be sent via UDP to the local broadcast address (all 1s), using port 4321.
EXERCISES:
bind
its input socket to IP address
INADDR_ANY
and port 4321.
Each line of output should begin with the IP address of the
source of the message, followed by the message itself. Note
that mixing printf
and write(1, ...,
...)
won't work very well because of UNIX buffering.
You'll want to use one or the other method exclusively. The
program should receive and echo input in an infinite loop.I've set up a test transmitter program that periodically broadcasts a message to port 4321. Your receiver should be able to pick up this broadcast (as well as any other messages sent by other students' transmitters).
read
from
the keyboard.
If your transmitter returns an error message to the effect of
"address already in use", you already have a copy of your
program bound to port 4321. Use the ps
command
to locate that
process and kill
to terminate it. This condition
will be more likely to occur in the next exercise.
fork()
to start a separate receiver process. The
UNIX fork()
system call starts a second process that
is an exact copy of the first process (executing the same code,
copies of all local and global variables). The only difference
is that fork()
returns the process id of the new
process to the old process, and returns 0 to the new process.
The C idiom for using fork()
looks like:
if ((pid = fork()) == 0) { /* code for new process (receiver) goes here */ } /* code for old process (transmitter) goes here */ kill(pid, 9); /* terminates other process */
Be sure to terminate the receiver process from within the transmitter process after the user has entered ^D.
When complete: Demonstrate the correct functionality of your program.