I am trying to write client/server program in c.
I am getting connection refused. I am not able to figure out what is the problem
Can anyone please help me.
This is the server
// include directories
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "unistd.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "netinet/in.h"
#include "strings.h"
#include "arpa/inet.h"
#include "math.h"
#define PORTNUM 1300
#define LISTENQ 10
#define BUFFER 1024
int main( int argc, char *argv[] )
{
int i, maxi, maxfd, listenfd, connfd, sockfd, flag, previousfd;
int nready, client[FD_SETSIZE];
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
fd_set rset, allset;
ssize_t n;
struct frame fpart, bufferedPart1,bufferedPart2 ;
char recvline[BUFFER], sendline[BUFFER];
/* First call to socket() function */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Socket Error");
exit(-1);
}
printf("I ma here");
/* Initialize socket structure */
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5000);
servaddr.sin_addr.s_addr = INADDR_ANY;
/* Now bind the host address using bind() call.*/
if((bind(sockfd,(struct sockaddr *)&servaddr, sizeof(struct sockaddr_in)))== -1)
{
perror("Bind Error");
exit(-1);
}
printf("I ma here");
/* Now start listening for the clients */
listen(listenfd, LISTENQ);
printf("I ma here");
flag = 0;
maxfd = listenfd; /* initialize */
maxi = -1; /* index into client[] array */
for (i = 0; i < FD_SETSIZE; i++)
client[i] = -1; /* -1 indicates available entry */
FD_ZERO(&allset);
FD_SET(listenfd, &allset);
for ( ; ; ) {
rset = allset; /* structure assignment */
nready = select(maxfd + 1, &rset, NULL, NULL, NULL);
if (FD_ISSET(listenfd, &rset)) {
/* new client connection */
clilen = sizeof(cliaddr);
printf("I ma here");
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
for (i = 0; i < FD_SETSIZE; i++)
if (client[i] < 0) {
client[i] = connfd; /* save descriptor */
break;
}
if (i == FD_SETSIZE)
perror("too many clients");
FD_SET(connfd, &allset); /* add new descriptor to set */
if (connfd > maxfd)
maxfd = connfd; /* for select */
if (i > maxi)
maxi = i; /* max index in client[] array */
if (--nready <= 0)
continue; /* no more readable descriptors */
}
for (i = 0; i <= maxi; i++) {
/* check all clients for data */
if ( (sockfd = client[i]) < 0)
continue;
if (FD_ISSET(sockfd, &rset)) {
if ( (n = read(sockfd, recvline, sizeof(recvline))) == 0) {
/* connection closed by client */
close(sockfd);
FD_CLR(sockfd, &allset);
client[i] = -1;
} }
if (--nready <= 0)
break; /* no more readable descriptors */
}
}
}
}
The server should be able to listen to more than one client. So I used select.
According to man 2 listen, the first argument should be the file descriptor of the socket that should be listened for connections.
In your server's code, listenfd is uninitialized. What you actually need to listen(2) on, is the socket with file descriptorsockfd.
Initialize listenfd as sockfd just before calling listen(2), or replace listenfd with sockfd on server's side, and it should work.
In addition, have a look at this question about when to use "..." and <...> in #include statement.
Related
I am currently trying to create a multiple client-server which enables server to perform both read and write functions in C language. I am able to read the data from the client using readfds and putting it as parameter in SELECT. When I added in writefds, the client fails to connect to the server. I am not sure what is the issue behind it, whether this is the correct method to transmit and receive data
This is the code for my server
#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h>
#include <errno.h>
#include <unistd.h> //close
#include <arpa/inet.h> //close
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros
#define TRUE 1
#define FALSE 0
#define PORT 8080
int main(int argc , char *argv[])
{
int opt = TRUE;
int master_socket , addrlen , new_socket , client_socket[30] ,
max_clients = 2 , activity, i , valread , sd;
int max_sd;
struct sockaddr_in address;
char buffer[1025]; //data buffer of 1K
fd_set readfds;
fd_set writefds;
char *message = "Welcome to Server\r\n";
//initialise all client_socket[] to 0 so not checked
for (i = 0; i < max_clients; i++)
{
//client_socket[i] = 0;
}
//create a master socket
if( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt,
sizeof(opt)) < 0 )
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
//type of socket created
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
//bind the socket to localhost port 8888
if (bind(master_socket, (struct sockaddr *)&address, sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("Listener on port %d \n", PORT);
if (listen(master_socket, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
addrlen = sizeof(address);
puts("Waiting for connections ...");
for(;;)
{
//clear the socket set
FD_ZERO(&readfds);
FD_ZERO(&writefds);
//add master socket to set
FD_SET(master_socket, &readfds);
FD_SET(master_socket, &writefds);
max_sd = master_socket;
//add child sockets to set
for ( i = 0 ; i < max_clients ; i++)
{
//socket descriptor
sd = client_socket[i];
//if valid socket descriptor then add to read list
if(sd > 0)
FD_SET( sd , &readfds);
//highest file descriptor number, need it for the select function
if(sd > max_sd)
max_sd = sd;
}
//wait for an activity on one of the sockets , timeout is NULL ,
//so wait indefinitely
activity = select( max_sd + 1 , &readfds , &writefds, NULL , NULL);
if ((activity < 0) && (errno!=EINTR))
{
printf("select error");
}
if (FD_ISSET(master_socket, &readfds))
{
if ((new_socket = accept(master_socket,
(struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
else {
printf("Connected to socket \n");
}
bzero(buffer, 1025);
int n=0;
read(new_socket, buffer, sizeof(buffer));
printf("From client: %s\t To client: ", buffer);
bzero(buffer, 1025);
//add new socket to array of sockets
for (i = 0; i < max_clients; i++)
{
//if position is empty
if( client_socket[i] == 0 )
{
client_socket[i] = new_socket;
printf("Adding to list of sockets as %d\n" , i+1);
}
}
}
else if(FD_ISSET(master_socket, &readfds)) {
printf("From client: %s\t To client : ", buffer);
bzero(buffer, 1025);
// copy server message in the buffer
while ((buffer[n++] = getchar()) != '\n')
;
write(new_socket, buffer, sizeof(buffer));
}
else{
//else its some IO operation on some other socket
for (i = 0; i < max_clients; i++)
{
sd = client_socket[i];
if (FD_ISSET( sd , &readfds))
{
//Check if it was for closing , and also read the
//incoming message
if ((valread = read( sd , buffer, 1024)) == 0)
{
close( sd );
client_socket[i] = 0;
}
//Echo back the message that came in
else
{
}
}
}
}//else
}
return 0;
}
This is the code for the client
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#define MAX 1000
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
int firstConnect = 1;
for (;;)
{
bzero(buff, sizeof(buff));
n = 0;
if(firstConnect==1) {
printf("Enter the string : ");
firstConnect = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
}
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server: %s\t To Server : ", buff);
while ((buff[n++] = getchar()) != '\n');
write(sockfd, buff, sizeof(buff));
if ((strncmp(buff, "exit", 4)) == 0)
{
printf("Client Exit...\n");
break;
}
}
}
int main()
{
printf("CLIENT");
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
// servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_addr.s_addr = inet_addr("127.8.1.0");
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0)
{
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// function for chat
func(sockfd);
// close the socket
close(sockfd);
}
As side node, it appears that you expect read to zero-terminate received data. That is not the case. The length of received data is in the return value of read, it must not be ignored.
It also appears that you expect write to find the end of the string you are sending. That doesn't happen. You must specify the exact length of the data you are sending, rather than the length of the buffer that contains the data.
send/write and recv/read functions work on binary data rather than zero-terminated strings and can send/receive less than the specified size or may return an error. Learn how to use these functions correctly by not ignoring the return value and handling errors and partial reads and writes.
I wrote a simple TCP echo server to handle multiple clients. It uses select() to get multiple connections.
Server Code:
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
int create_listener(uint16_t port) {
int listen_fd;
struct sockaddr_in name;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
perror ("socket");
exit(EXIT_FAILURE);
}
bzero(&name, sizeof(name));
name.sin_family = AF_INET;
name.sin_addr.s_addr = htonl(INADDR_ANY);
name.sin_port = htons(port);
if (bind(listen_fd, (struct sockaddr *) &name, sizeof(name)) < 0) {
perror ("bind");
exit(EXIT_FAILURE);
}
return listen_fd;
}
int read_from_client(int fd) {
char buffer[100];
int nbytes;
nbytes = read(fd, buffer, 100);
if (nbytes < 0) {
perror("read");
exit(EXIT_FAILURE);
}
else if (nbytes == 0) {
return -1;
}
else {
fprintf(stderr, "Server: got message: %s\n", buffer);
write(fd, buffer, strlen(buffer) + 1);
return 0;
}
}
int main(int argc, char *argv[]) {
int listen_fd;
uint16_t port = 22000;
fd_set active_fd_set, read_fd_set;
int i;
struct sockaddr_in servaddr;
/* Create the socket and set it up to accept connections. */
listen_fd = create_listener(port);
if (listen(listen_fd, 10) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
/* Initialize the set of active sockets. */
FD_ZERO(&active_fd_set);
FD_SET(listen_fd, &active_fd_set);
while (1) {
/* Block until input arrives on one or more active sockets. */
read_fd_set = active_fd_set;
if (select(FD_SETSIZE, &read_fd_set, NULL, NULL, 0) < 0) {
perror("select");
exit(EXIT_FAILURE);
}
/* Service all the sockets with input pending. */
for (i = 0; i < FD_SETSIZE; ++i) {
if (FD_ISSET(i, &read_fd_set)) {
if (i == listen_fd) {
/* Connection request on original socket. */
int new_fd;
new_fd = accept(listen_fd, (struct sockaddr *) NULL, NULL);
if (new_fd < 0) {
perror ("accept");
exit(EXIT_FAILURE);
}
FD_SET(new_fd, &active_fd_set);
}
else {
/* Data arriving on an already-connected socket. */
if (read_from_client(i) < 0) {
close(i);
FD_CLR(i, &active_fd_set);
}
}
}
}
}
return 0;
}
Client code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
int sockfd, n;
char sendline[100];
char recvline[100];
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(22000);
inet_pton(AF_INET, "127.0.0.1", &(servaddr.sin_addr));
connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
while (1) {
bzero(sendline, 100);
bzero(recvline, 100);
fgets(sendline, 100, stdin);
write(sockfd, sendline, strlen(sendline) + 1);
read(sockfd, recvline, 100);
printf("%s", recvline);
}
return 0;
}
The problem is when I run server in one terminal and run two clients in another two terminals. If I use Ctrl+C to terminate one client, the server automatically terminates. I'm wondering why the server acts this way. What I'm expecting is the server runs forever. When client 1 terminates, server should still has a live connection with client 2.
Looks like you're hitting the exit in read_from_client. In general, in a server that serves multiple clients, you probably don't want to exit when you have a failure with one of the client connections.
While trying to implement a server and client, I noticed that the client was writing to stdout instead
of through the network. I figured out that the file descriptor being returned by connect() is always zero, which explains why it was writing to stdout. But I can not figure out why connect() always returns zero instead of a valid socket. All the articles on the web I found with the same problem were due to precedence issues with wrapping if() around the connect() call. But I haven't done that, any help would be appreciated.
server code
int setUpServer(struct fuzzerObj *ptr, int *firstClient)
{
/* Declarations */
int hostSocket, yes = 1, rtrn, clientfd;
union
{
struct sockaddr_in in;
}address;
/* Create Socket */
hostSocket = socket(AF_INET, SOCK_STREAM, 0);
if(hostSocket < 0)
{
errorHandler("Could not create socket\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
/* Reuse Address */
rtrn = setsockopt(hostSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if(rtrn < 0)
{
errorHandler("Couldn't Reuse Address\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
/* Set Up Struct */
address.in.sin_len = sizeof(address.in);
address.in.sin_family = AF_INET;
address.in.sin_port = htons(BBPORT_NUMBER);
address.in.sin_addr.s_addr = htonl(INADDR_ANY);
memset(address.in.sin_zero, 0, sizeof(address.in.sin_zero));
/* Bind Address to Socket */
rtrn = bind(hostSocket, (struct sockaddr*) &address, address.in.sin_len);
if(rtrn < 0)
{
errorHandler("Can't Bind Address to Socket\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
/* listen */
rtrn = listen(hostSocket, ptr->numberOfClients);
if(rtrn < 0)
{
errorHandler("Can't Listen\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
while(1)
{
rtrn = acceptClient(hostSocket, &clientfd);
if(rtrn < 0)
{
printf("Can't Accept Client\n");
return -1;
}
break;
}
*firstClient = clientfd;
return 0;
}
client code
#include <CoreFoundation/CoreFoundation.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#define BLACKBOX_PORT 9696
int main(int argc, char *argv[])
{
/* Check To See If an argument was passed */
if(argc < 2)
{
printf("No enough Arguments\n");
return -1;
}
/* Declaration's */
const char *ip = argv[1];
int sockfd, fd, rtrn;
char *outBuf;
struct sockaddr_in servaddr;
/* Get Socket to Connect to Fuzz Server */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
{
perror("Can't Create Socket");
return -1;
}
/* Fill Out Struct */
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(BLACKBOX_PORT);
inet_pton(AF_INET, ip, &servaddr.sin_addr);
/* Attempt Connection */
fd = connect(sockfd,(struct sockaddr *)&servaddr, sizeof(servaddr));
if(fd < 0)
{
perror("Can not connect to BlackBox Fuzz server");
return -1;
}
/* Allocate Space in Memory for Outgoing Connection */
rtrn = asprintf(&outBuf, "Mac OSX 10.9\n");
if(rtrn < 0)
{
perror("Copy Error");
return -1;
}
/* Send Data to Fuzzer via Socket */
rtrn = send(fd, outBuf, strlen(outBuf), 0);
if(rtrn < 0)
{
perror("Can't write Data to BlackBox Server");
return -1;
}
free(outBuf);
return 0;
}
Upon successfully calling connect(), the sockfd is connected. The 0 return value indicates that the call is successful. If the value was not 0, it would have indicated an error, and that the connection attempt has failed or is not yet completed (if the connect is non-blocking).
After determining that connect() has succeeded, call send() on the sockfd, not on the return value of the connect() call.
rtrn = send(sockfd, outBuf, strlen(outBuf), 0);
I'm trying to make a server and client. But when I try to connect the client to the server, I get connection refused. The other answers on stack overflow said to make sure you have listen() and accept(), which I do, and to check the firewalls. So I turned off all the firewalls just to make sure.
I still get connection refused, so I tried ./telnet 10.1.10.13 9696, and got:
Trying 10.1.10.13...
telnet: connect to address 10.1.10.13: Connection refused
telnet: Unable to connect to remote host
Here's the code for the server
int setUpServer(struct fuzzerObj *ptr)
{
/* Declarations */
int hostSocket, yes = 1, rtrn;
union
{
struct sockaddr_in in;
}address;
/* Create Socket */
hostSocket = socket(AF_INET, SOCK_STREAM, 0);
if(hostSocket < 0)
{
errorHandler("Could not create socket\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
/* Reuse Address */
rtrn = setsockopt(hostSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if(rtrn < 0)
{
errorHandler("Couldn't Reuse Address\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
errno = 0;
/* Set Up Struct */
address.in.sin_len = sizeof(address.in);
address.in.sin_family = AF_INET;
address.in.sin_port = BBPORT_NUMBER;
address.in.sin_addr.s_addr = htonl(INADDR_ANY);
memset(address.in.sin_zero, 0, sizeof(address.in.sin_zero));
/* Bind Address to Socket */
rtrn = bind(hostSocket, (struct sockaddr*) &address, address.in.sin_len);
if(rtrn < 0)
{
errorHandler("Can't Bind Address to Socket\n", FUNCTION_ID_SET_UP_SERVER);
perror("");
return -1;
}
/* listen */
rtrn = listen(hostSocket, ptr->numberOfClients);
if(rtrn < 0)
{
errorHandler("Can't Listen\n", FUNCTION_ID_SET_UP_SERVER);
return -1;
}
while(1) acceptClient(hostSocket);
return 0;
}
int acceptClient(int fd)
{
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
int clientFd = accept(fd, (struct sockaddr *) &addr, &addr_len);
if(clientFd < 0)
{
printf("Can't Accept Client\n");
return -1;
}
return clientFd;
}
and the code for the client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#define BLACKBOX_PORT 9696
int main(int argc, char *argv[])
{
/* Check To See If an argument was passed */
if(argc < 2)
{
printf("No enough Arguments\n");
return -1;
}
/* Declaration's */
const char *ip = argv[1];
int sockfd, fd, rtrn;
char *inBuf;
struct sockaddr_in servaddr,cliaddr;
socklen_t len = sizeof(cliaddr);
/* Get Socket to Connect to Fuzz Server */
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
{
perror("Can't Create Socket");
return -1;
}
/* Fill Out Struct */
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(BLACKBOX_PORT);
inet_pton(AF_INET, ip, &servaddr.sin_addr);
/* Attempt Connection */
fd = connect(sockfd,(struct sockaddr *)&servaddr, sizeof(servaddr));
if(fd < 0)
{
perror("Can not connect to BlackBox Fuzz server");
return -1;
}
/* Allocate Space in Memory for Incoming Connection */
inBuf = (char *) malloc(1025);
if(inBuf == NULL)
{
perror("Mem Error");
return -1;
}
/* Read From Socket */
rtrn = read(fd, inBuf, 1024);
if(rtrn < 0)
{
perror("Can't Read Data From BlackBox Server");
return -1;
}
printf("Received Data: %s\n", inBuf);
free(inBuf);
return 0;
}
Output from client:
./client 10.1.10.13
Can not connect to BlackBox Fuzz server
Connection refused
Any help would be appreciated, thanks.
Assuming that you're running this code on a little-endian machine, you need to use htons() when assigning the port number on the server side too.
(On big-endian machines htons() is a "no-op", but you should always use it to ensure portability)
After looking at Beej's guide to network programming, I am trying to redo my server.c using select instead of fork. I am not too sure what is going wrong; my program compiles, but doesn't accept connections. I know that my loop containing i<=fdmax isn't functioning properly, but I can't figure out why. It seems like the if statements are not working appropriately.
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/select.h>
#define Connections 5
void SignalCatcher(int signum)
{
wait3(NULL,WNOHANG, NULL);
//wait(-1);
}
int main(int argc, char**argv)
{
int listenfd,connfd,n, i;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
pid_t childpid;
char mesg[1000];
FILE *inputFile;
inputFile = fopen("movie.txt", "r");
char returnMsg[1000];
int fdmax, newfd;
fd_set readfd;
fd_set mastersocket;
FD_ZERO(&mastersocket);
FD_ZERO(&readfd);
//Creating socket number
listenfd=socket(AF_INET,SOCK_STREAM,0);
//Setting up the internet address
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(32000);
bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
//Listening for clients
listen(listenfd,1024);
FD_SET(listenfd, &mastersocket);
fdmax=listenfd;
//signal(SIGCHLD, SIG_IGN);
signal(SIGCHLD, SignalCatcher);
//Infinite loop that waits for/accepts connections.
for(;;)
{
readfd = mastersocket;
clilen=sizeof(cliaddr);
if(select(fdmax+1, &readfd, NULL, NULL, NULL) == -1) {
perror("select");
exit(4);}
//connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen);
for(i=0; i<=fdmax;i++)
{
if (FD_ISSET(i, &readfd)){
if(i==listenfd){
printf("-SUCCESS\n");
clilen = sizeof cliaddr;
connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen); }
if (connfd!=-1)
{
// if ((childpid = fork()) == 0)
// {
close (listenfd);
for(;;)
{
n = recvfrom(connfd,mesg,1000,0,(struct sockaddr *)&cliaddr,&clilen);
if (n == -1 /*&& errno == EWOULDBLOCK*/) continue;
else if(n==0) break;
//sendto(connfd,mesg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
//write(connfd , mesg , strlen(mesg)); //both work
//write(connfd , "" , 1);
printf("-------------------------------------------------------\n");
printf("%d",listenfd);
mesg[n] = 0;
printf("Received the following:\n");
printf("%s",mesg);
printf("-------------------------------------------------------\n");
}
// }
close(connfd);
} //if connfd!=-1
}
} //for i<=fdmax
}
}
You can answer this question yourself by examining the functions' return values. In network programming, the usual idiom is something along the lines of:
if (foo() < 0) {
fprintf(stderr, "foo: %s\n", strerror(errno));
/* recover from error or... */
exit(EXIT_FAILURE);
}
...where foo() is one of bind(), listen(), accept(), send*/recv*() and so on.
Go ahead and try. errno will tell you what's wrong.
Besides, it's unclear why you are using select() at all. All you do is listen on a single socket, and you close it as soon as someone connects. Instead, you could just accept(listenfd).
firstly you should not close the listening fd it should be close while exiting the program. secondly we need to accept all incoming connections that are queued up on the listening socket.then if listening socket is not readable then an existing connection must be readable, so read the data for that connection. I just read once but u can read in loop for that connection until recv fails.
following code change should work:
//Infinite loop that waits for/accepts connections.
for(;;)
{
readfd = mastersocket;
clilen=sizeof(cliaddr);
if(select(fdmax+1, &readfd, NULL, NULL, NULL) == -1) {
perror("select");
exit(4);}
//connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen);
for(i=0; i<=fdmax;i++)
{
if (FD_ISSET(i, &readfd)){
if(i==listenfd){
printf("-SUCCESS\n");
clilen = sizeof cliaddr;
connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen);
if (connfd!=-1)
{
FD_SET(connfd, &mastersocket);
if (connfd > fdmax) {
fdmax = connfd;
}
}
}
else
{
n = recvfrom(i,mesg,1000,0,(struct sockaddr *)&cliaddr,&clilen);
if ((n == -1 /*&& errno == EWOULDBLOCK*/) || (n==0)) {
close (i);
FD_CLR (i, &mastersocket);
if (i == fdmax)
{
while (FD_ISSET(fdmax, &mastersocket) == 0)
fdmax -= 1;
}
}
//sendto(i,mesg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
//write(i , mesg , strlen(mesg)); //both work
//write(i , "" , 1);
printf("-------------------------------------------------------\n");
printf("%d",listenfd);
mesg[n] = 0;
printf("Received the following:\n");
printf("%s",mesg);
printf("-------------------------------------------------------\n");
}
}
} //for i<=fdmax
}
I tried your code with changes and its working fine to me.
Also if you want only one client communicate with server at a time then enable the while loop for reading client data.
server.c
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/select.h>
#define Connections 5
void SignalCatcher(int signum)
{
wait3(NULL,WNOHANG, NULL);
//wait(-1);
}
int main(int argc, char**argv)
{
int listenfd,connfd,n, i;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
pid_t childpid;
char mesg[1000];
FILE *inputFile;
inputFile = fopen("movie.txt", "r");
char returnMsg[1000];
int fdmax, newfd;
fd_set readfd;
fd_set mastersocket;
FD_ZERO(&mastersocket);
FD_ZERO(&readfd);
//Creating socket number
listenfd=socket(AF_INET,SOCK_STREAM,0);
//Setting up the internet address
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(32000);
bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
//Listening for clients
listen(listenfd,1024);
FD_SET(listenfd, &mastersocket);
fdmax=listenfd;
//signal(SIGCHLD, SIG_IGN);
signal(SIGCHLD, SignalCatcher);
//Infinite loop that waits for accepts connections.
for(;;)
{
readfd = mastersocket;
clilen=sizeof(cliaddr);
if(select(fdmax+1, &readfd, NULL, NULL, NULL) == -1) {
perror("select");
exit(4);}
//connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen);
for(i=0; i<=fdmax;i++)
{
if (FD_ISSET(i, &readfd)){
if(i==listenfd){
printf("-SUCCESS\n");
clilen = sizeof cliaddr;
connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&clilen);
if (connfd!=-1)
{
FD_SET(connfd, &mastersocket);
if (connfd > fdmax) {
fdmax = connfd;
}
}
}
else
{
//while(1) {
n = recvfrom(i,mesg,1000,0,(struct sockaddr *)&cliaddr,&clilen);
if ((n == -1 /*&& errno == EWOULDBLOCK*/) || (n==0)) {
close (i);
FD_CLR (i, &mastersocket);
if (i == fdmax)
{
while (FD_ISSET(fdmax, &mastersocket) == 0)
fdmax -= 1;
}
// break;
}
//sendto(i,mesg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
//write(i , mesg , strlen(mesg)); //both work
//write(i , "" , 1);
printf("-------------------------------------------------------\n");
printf("%d",listenfd);
mesg[n] = 0;
printf("Received the following:\n");
printf("%s",mesg);
printf("-------------------------------------------------------\n");
}
//} /* end of while */
}
} //for i<=fdmax
}
}
client.c
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define SERVER_PORT 32000
int main (int argc, char *argv[]) {
int sd, rc, i;
struct sockaddr_in localAddr, servAddr;
struct hostent *h;
char message[1000] ;
servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons( SERVER_PORT );
/* create socket */
sd = socket(AF_INET, SOCK_STREAM, 0);
if(sd<0) {
perror("cannot open socket ");
exit(1);
}
/* bind any port number */
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(0);
rc = bind(sd, (struct sockaddr *) &localAddr, sizeof(localAddr));
if(rc<0) {
printf("%s: cannot bind port TCP %u\n",argv[0],SERVER_PORT);
perror("error ");
exit(1);
}
/* connect to server */
rc = connect(sd, (struct sockaddr *) &servAddr, sizeof(servAddr));
if(rc<0) {
perror("cannot connect ");
exit(1);
}
while(1)
{
printf("Enter message : ");
scanf("%s" , message);
rc = send(sd, message, strlen(message) + 1, 0);
if(rc<0) {
perror("cannot send data ");
close(sd);
exit(1);
}
printf("To_server: data%u sent (%s)\n",strlen(message),message);
}
return 0;
}