Hi!
I am relatively inexperienced in socket programming but as it happens
I can run away from the inevitable no longer..
I am a student and am writing a P2P chat program as part of a course.
I have the initiator function (essentially sends a connect request to
a user input host-> only once..i have to correct that bit later)as
well as the listener function(essentially a server program wriiten as
a procedure) in separate C files. My driver program forks a
process..one just calls the initiator() function, the other calls the
listener()..it returns.
Now when i run the program on 2 different machines,(By the way I am
using TCP sockets for sending and listening)..a connection is
established and the message i sent as a connect message is sent and
received correctly too.
But as soon as the initiator of one machine is done sending, I get an
error by its listener: "bind: address already in use"
and the connection is aborted.
This after having using the setsockopt system call in the listener.
my code listing follows:
/*
initiator.c attempts to connect to a machine
*/
#include "header.h"
void initiator(char *host)
{
struct sockaddr_in peeraddr;
int talk;
int size;
int bytes_sent;
struct hostent *peer;
char mesg[]= "Hi! I wanna chat with you!\n";
if ((peer = gethostbyname(host)) == NULL) {
herror("gethostbyname");
exit(1);
}
if ((talk = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
// printf("the sending address is %s \n",inet_ntoa(*((struct in_addr
//*)peer->h_addr)));
peeraddr.sin_family = AF_INET;
peeraddr.sin_port = htons(CHATPORT);
peeraddr.sin_addr = *((struct in_addr *) peer->h_addr);
memset(&(peeraddr.sin_zero), '\0', 8);
size = sizeof(peeraddr);
if( connect(talk,(struct sockaddr *)&peeraddr,sizeof(struct
sockaddr))==-1){
perror("Connect");
exit(1);
}
printf(" Hey I am connected!\n");
bytes_sent=sendto(talk,mesg, strlen(mesg),0,(struct sockaddr
*)&peeraddr, size);
if(bytes_sent==-1)
{
perror("send");
exit(1);
}
}
/*
* listener.c
*/
Essentially Beejs code using the select option
/*
* main.c
*/
#include "header.h"
int main(int argc, char *argv[])
{
int pid;
while(1)
{
pid=fork();
if(pid==0) // child process
{
initiator(argv[1]);
}
listener();
}
return 0;
}
I'd really appreciate telling me of all the conceptual mistakes that
I am making..
Thanks a lot.
Regards
Shalini