I have written a code in c to work on Linux. I m looking to write a program to chat, but being a newbie in this field, I am facing problems. Please help me with that. All I want to design is a wall like command. A server to listen for connections, and echos back the message to all the connected clients. The most gruesome prob;lem I m facing is to make my server listen for multiple connections through a single port, because I can't ask all the clients to connect to different ports. Help me with some working code, I can learn from. If any one could give me the code to simply accept the connection and echo back whatever a client has sent and the welcome message. To the best if any one can help me use the same port for multiple connecions.
Server Code ......
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define DestIP "127.0.0.1"
#define SourcePort 12004
char *msg = "Hello World !";
main ()
{
int sockfd;
struct sockaddr_in source_addr;
if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
{
printf ("Cannot create socket !\n");
exit (-1);
}
source_addr.sin_family = AF_INET;
source_addr.sin_port = htons(SourcePort);
source_addr.sin_addr.s_addr = htonl(INADDR_ANY);
memset (&(source_addr.sin_zero), '\0', 8);
if (bind (sockfd, (struct sockaddr *) &source_addr, sizeof(struct sockaddr))== -1)
{
printf ("Unable to bind connection to the OS.");
exit(-1);
}
for (;
{
msg = "";
recv (sockfd, msg, sizeof (msg), 0);
printf ("%s", msg);
}
}
________________________________________________________________________
Client Code:......
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define DestIP "127.0.0.1"
#define DestPort 12004
char *msg="Hello World !";
main()
{
int sockfd;
struct sockaddr_in dest_addr;
if (sockfd=socket(AF_INET,SOCK_STREAM,0)==-1)
{
printf("Cannot create socket !\n");
exit(-1);
}
dest_addr.sin_family=AF_INET;
dest_addr.sin_port=htons(DestPort);
dest_addr.sin_addr.s_addr=inet_addr(DestIP);
memset(&(dest_addr.sin_zero),'\0',8);
if ((connect(sockfd,(struct sockaddr *)&dest_addr, sizeof(struct sockaddr)))==-1)
{
printf("Unable to connect to remote host !");
exit(-1);
}
if (send(sockfd, msg, sizeof(msg),0)==-1)
{
printf("Error sending data...");
exit(-1);
}
}
________________________________________________________________________
Please help me write a better code.