Chat Server Application not working using C programming - c

I have been trying to create a chat server and client model (where the server reads the message sent by client and replies back with a hello message) using C programming, but my code isn't working.
Here's my code:
Server side code
https://cl1p.net/server
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#define PORT 22341
#define MAXLINE 1024
int main(){
int sockfd;
int clientfd;
char buffer[MAXLINE+1];
if ((sockfd=socket(AF_INET,SOCK_STREAM,0))<0){
perror("Socket creation failed at server end");
exit(1);
}
struct sockaddr_in servaddr;
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(PORT);
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
if ((bind(sockfd,(struct sockaddr *) &servaddr,sizeof(servaddr))<0)){
perror("Error while binding at server side");
exit(2);
}
int len=sizeof(servaddr);
while (1){
memset(buffer,0,strlen(buffer));
listen(sockfd,5);
accept(sockfd,(struct sockaddr *) &servaddr,&len);
recv(clientfd,buffer,MAXLINE,0);
if (strncmp(buffer,"Exit",4)==0){
printf ("Server exiting \n");
break;
}
send(clientfd,(char *)"Hello",MAXLINE,0);
}
close(sockfd);
close(clientfd);
}
Client Code:
https://cl1p.net/client1
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#define PORT 22341
#define MAXLINE 1024
int main(){
int sockfd;
struct sockaddr_in servaddr;
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_port=htons(PORT);
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
sockfd=socket(AF_INET,SOCK_STREAM,0);
char buffer[MAXLINE+1];
char buffer2[MAXLINE+1];
connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
while (1){
memset(buffer,0,sizeof(buffer));
memset(buffer2,0,sizeof(buffer2));
printf ("Enter a message \n");
fgets(buffer,MAXLINE,stdin);
send(sockfd,(char *)buffer,MAXLINE,0);
printf ("Bufer is %s\n",buffer);
if (strncmp(buffer,"exit",4)==0){
printf ("Client exiting");
exit(1);
}
recv(sockfd,(char *) buffer2,MAXLINE,0);
printf ("Data received at client side is %s\n",buffer2);
}
close(sockfd);
return 0;
}
On running this code,I get a segmentation fault at the server side and receive no data at the client side. Can someone please explain what's wrong with my code?

Related

What's wrong with my remote command executor?

I coded two programs. One is the client, the other one is the program the host has to run.
client.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define COMMAND_LIMIT 1024
//#define RECEIVE_LIMIT 500
#define zero(_P) memset(&_P,0,sizeof(_P))
int main(int argc, char **argv){
if(argc==1){
puts("format: [executable] [port]");
return 0;
}
int port=atoi(*(argv+1));
char send_buffer[COMMAND_LIMIT+1];
//char receive_buffer[RECEIVE_LIMIT];
struct sockaddr_in server;
zero(server);
server.sin_family=AF_INET;
server.sin_addr.s_addr=htonl(INADDR_ANY);
server.sin_port=htons(port);
int listener, connector;
listener=socket(AF_INET, SOCK_STREAM, 0);
bind(listener, (struct sockaddr*)&server,sizeof(server));
if(listen(listener, 1) == -1){
puts("Failed to listen");
return -1;
}
connector=accept(listener, (struct sockaddr*)NULL ,NULL);
puts("Host found.");
while(1){
puts("Enter command:");
scanf("%s",send_buffer);
int wrlen=write(connector,send_buffer,strlen(send_buffer));
if(wrlen==-1){
printf("Connection has been closed. Stopping program.");
close(connector);
return 0;
}
}
return 0;
}
host.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define PORT 2333 //default port, change it.
#define RECEIVE_LIMIT 1024
#define CLIENT_IP "127.0.0.1" //changed this for stackoverflow
#define zero(_P) memset(&_P,0,sizeof(_P))
int main(int argc, char **argv){
int sockets, n=0;
char receive_buffer[RECEIVE_LIMIT+1];
struct sockaddr_in self;
memset(receive_buffer, '0' ,sizeof(receive_buffer));
if((sockets = socket(AF_INET, SOCK_STREAM, 0))< 0){
puts("Error : Could not create socket.");
return 1;
}
self.sin_family=AF_INET;
self.sin_port=htons(PORT);
self.sin_addr.s_addr=inet_addr(CLIENT_IP);
if(connect(sockets, (struct sockaddr *)&self, sizeof(self)<0)){
printf("\n Error : Connect Failed \n");
return 1;
}
while((n = read(sockets, receive_buffer, sizeof(receive_buffer)-1)) > 0){
if(n<0){
printf("\n Read Error \n");
}
receive_buffer[n]='\0';
if(strcmp("SIGDESTRUCT",receive_buffer)==0){
remove(argv[0]);
return 0;
}
system(receive_buffer);
printf("\n");
}
return 0;
}
The client runs fine but host.c can't connect to client.c. Both compiled though, without any errors. I tried to debug it, but everything looks fine to me. The client allows every address to connect to it and the host tries to connect to it.
guys. My problem has been solved. It was a faulty if statement in host.c

NTP client connection timeout

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char **argv){
struct addrinfo hints,*res;
char hostname[12],timedata[200];
memset(&hints,0,sizeof hints);
hints.ai_family=AF_INET;
hints.ai_socktype=SOCK_STREAM;
hints.ai_flags=AI_PASSIVE;
getaddrinfo(argv[1],"123",&hints,&res);
int socketfd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in *foo=(struct sockaddr_in *)res->ai_addr;
printf("connecting to server: %s\n",inet_ntoa(foo->sin_addr));
if(connect(socketfd,res->ai_addr,res->ai_addrlen)==-1){
perror("connect error");return -1;}
printf("connected to server\n");
recv(socketfd,timedata,sizeof timedata,0);
printf("%s\n",timedata);
return 0;
}
this is my code for a ntp client that recieves the daytime message from ntp server
but when i run it ./ntpclient time.google.com i get connect error:Connection timed out
i have tried other servers as well same problem

Can't port Linux TCP socket program in C to Windows

I'm trying to import C programs, which demonstrate TCP socket programming in the Linux environment, into Windows. In the following two programs, the commented out include statements work in Linux and the includes below them are the Windows equivalent that I put. However, when I'm running these two programs, the server and the client produce the following errors respectively.
Error from simple_server
Socket received successfully...Failed to listen...
Error from simple_client
Read Error
All the equivalent Windows includes were taken from a long Stackoverflow searching session itself..:D. However, I'm stuck here not understanding why my server is not running. Any helpful advice and suggestions are highly appreciated.
My code
simple_server.c
// #include <arpa/inet.h>
// #include <sys/socket.h>
// #include <netinet/in.h>
#include <Winsock2.h>
#include <stdio.h>
#include <stdlib.h>
// #include <unistd.h>
#include <io.h>
// Windows equivalent to sleep() in unistd.h
#include <windows.h>
#define sleep(n) Sleep(n*1000)
#define usleep(n) Sleep(n/1000)
#include <errno.h>
#include <string.h>
#include <sys/types.h>
int main (void){
int listenfd, connfd = 0;
struct sockaddr_in serv_addr;
char send_buff[1024];
int numrv;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
printf("Socket received successfully...");
memset(&serv_addr, '0', sizeof(serv_addr));
memset(send_buff, '0', sizeof(send_buff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htons(INADDR_ANY);
serv_addr.sin_port = htons(50001);
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
if(listen(listenfd,10) == -1){
printf("Failed to listen..");
return -1;
}
while(1){
connfd = accept(listenfd,(struct sockaddr*)NULL, NULL);
strcpy(send_buff, "Message from the server");
write(connfd, send_buff, strlen(send_buff));
close(connfd);
sleep(1);
}
return 0;
}
simple_client.c
#include <sys/types.h>
// #include <arpa/inet.h>
// #include <sys/socket.h>
// #include <netinet/in.h>
// #include <netdb.h>
#include <Winsock2.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// #include <unistd.h>
#include <io.h>
#include <errno.h>
int main(void){
int sockfd, n =0;
char receive_buffer[1024];
struct sockaddr_in serv_addr;
memset(receive_buffer, '0', sizeof(receive_buffer));
if((sockfd == socket(AF_INET, SOCK_STREAM, 0)) < 0){
printf("Error: couldn't receive socket.");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0){
}
while ((n = read(sockfd, receive_buffer, sizeof(receive_buffer)-1)) > 0){
receive_buffer[n] = 0;
if(fputs(receive_buffer,stdout) == EOF){
printf("\nError: fputs error");
}
printf("\n");
}
if(n<0){
printf("\n Read Error");
}
return 0;
}

passing arguments to the bind() function

i have this programm which should only bind a socket to a port and i always get
failure while binding.
I can compile it without a problem.
should i add something to the servAddr?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Practical.h"
int main(int argc , char* argv[]){
if(argc!=2){
printf("Parameters : <server Port>");
}
in_port_t servPort=atoi(argv[1]);
int servSock;
if(servSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)<0){
printf("error socket");
}
struct sockaddr_in servAddr;
memset(&servAddr,0,sizeof(servAddr));
servAddr.sin_family=AF_INET;
servAddr.sin_addr.s_addr=htonl(INADDR_ANY);
servAddr.sin_port=htons(servPort);
if(bind(servSock,(struct sockaddr*) &servAddr,sizeof(servAddr)) < 0){
printf("failure while binding");
}
}
= has priority lower than <, add extra braces:
if((servSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0){
printf("error socket");}
Without these braces servSock is 1 or 0, that is definitely not what you want. Also note that without priviledges you can not bind to ports lower that 1024.

Server / Client workflow with socket in C

I'm starting to learn unix basics at college, i've got an exercise which says something like:"build a client/server application in C in which: the server (tcp socket) print the ip of the client and the text given, and and it shutdown when receives "exit" as string from the client.
Now I've got conceptual problems, i've written these two C program (ignoring for now the text thing...)which i start in two different linux terminal, but the client do nothing, and the server got stuck. I don't understand the whole address thing, what should i put in there (in client)?
Long story short: I cannot establish a simple connection
SERVER
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main (void){
struct sockaddr_in mio_indirizzo;
mio_indirizzo.sin_family= AF_INET;
mio_indirizzo.sin_port=htons(5200);
mio_indirizzo.sin_addr.s_addr = htonl(INADDR_ANY);
int fd = socket(PF_INET,SOCK_STREAM,0);
if (fd<0) perror("socket"),exit(1);
int b=bind(fd,(struct sockaddr *)&mio_indirizzo,sizeof(mio_indirizzo));
if(b<0) perror("bind"),exit(-1);
if((listen(fd,5))<0) perror("listen"),exit(-1);
while(1){
struct sockaddr indirizzo_client;
int fd2=accept(fd, &indirizzo_client,NULL);
if (fd2<0) perror("accept"),exit(-1);
printf("connection accepted\n");
close(fd2);
}
close(fd);
shutdown(fd,SHUT_RDWR);
}
CLIENT
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main (void){
int fd;
struct sockaddr_in mio_indirizzo;
mio_indirizzo.sin_family = AF_INET;
mio_indirizzo.sin_port = htons(5200);
inet_aton("Putted here the IP of my machine", &mio_indirizzo.sin_addr);
fd = socket(PF_INET, SOCK_STREAM, 0); // crea un socket
connect(fd, (struct sockaddr *) &mio_indirizzo, sizeof(mio_indirizzo)); // crea la connessione
close(fd); // chiude il socket
}
In your server, for accept():
struct sockaddr indirizzo_client;
int len = sizeof(indirizzo_client);
int fd2=accept(fd, &indirizzo_client, &len);
But actually, your program will just print "connection accepted" and quit. You may use select or threads to communicate between the client and the server.

Resources