client server programming - buffer written - c++

I am trying to develop client server program in c++ in which client is TCP echo client while server is TCP concurrent server using single process(using select system call). However i am succeed to develop it but problem with written buffer.
Server is writing some extra character from previous message after some message exchanged bet client and server,In starting it working fine for some message interchanged.
I am not getting why this happened?
//client code
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
#define MAXLINE 4096 /*max text line length*/
#define srv_PORT 3000 /*port*/
int main(int argc,char **argv)
{
int sockfd;
struct sockaddr_in srvaddr;
int sendchars,recvchar;
char buf[MAXLINE];
if (argc !=2)
{
cerr<<"Usage: Femto: <IP address of the srv"<<endl;
exit(1);
}
//Create a socket for the client
if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0)
{
cerr<<"Problem in creating the socket"<<endl;
exit(1);
}
//Creation of the socket
memset(&srvaddr, 0, sizeof(srvaddr));
srvaddr.sin_family = AF_INET;
srvaddr.sin_addr.s_addr= inet_addr(argv[1]);
srvaddr.sin_port = htons(srv_PORT);
//Connection of the client to the socket
if (connect(sockfd, (struct sockaddr *) &srvaddr, sizeof(srvaddr))<0)
{
cerr<<"Problem in connecting to the server"<<endl;
exit(1);
}
while (fgets(buf,sizeof(buf), stdin))
{
int n;
buf[MAXLINE]='\0';
sendchars=strlen(buf);
write(sockfd,buf,sendchars);
for(recvchar=0;recvchar<sendchars;recvchar+=n)
{
n=read(sockfd,&buf[recvchar],sendchars-recvchar);
if(n<0)
{
cerr<<"Read faild"<<endl;
}
cout<< "String received from the FGW: ";
fputs(buf, stdout);
}
}
}
//server code
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <sys/select.h>
#include <sys/time.h>
using namespace std;
#define MAXLINE 4096 /*max text line length*/
#define srv_PORT 3000 /*port*/
#define LISTENQ 65535
int main (int argc, char **argv)
{
int msock,ssock;
fd_set rfds;
fd_set afds;
int fd,nfds;
socklen_t client_len ;
char buf[MAXLINE];
struct sockaddr_in clientaddr, srvaddr;
if ((msock = socket (AF_INET, SOCK_STREAM, 0)) <0)
{
cerr<<"Problem in creating the socket"<<endl;
exit(1);
}
srvaddr.sin_family = AF_INET;
srvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
srvaddr.sin_port = htons(srv_PORT);
bind (msock, (struct sockaddr *) &srvaddr, sizeof(srvaddr));
listen (msock, LISTENQ);
nfds=getdtablesize();
FD_ZERO(&afds);
FD_SET(msock,&afds);
while(1)
{
memcpy(&rfds,&afds,sizeof(rfds));
if(select(nfds,&rfds,(fd_set *)0,(fd_set *)0,(struct timeval * )0)<0)
{
cerr<<"Error in select";
// exit(1);
}
if(FD_ISSET(msock,&rfds))
{
//int ssock;
ssock= accept(msock,(struct sockaddr *)&clientaddr,&client_len);
if(ssock<0)
{
cerr<<"Accept error";
}
FD_SET(ssock,&afds);
}
for(fd=0;fd<nfds;++fd)
if(fd!=msock && FD_ISSET (fd,&rfds))
{
int cc;
char buf[MAXLINE];
cc=read(fd,buf,sizeof(buf));
cout<<"String received from and resent to the client:"<<endl;
puts(buf);
if(cc<0)
{
cerr<<"Read error"<<endl;
exit(1);
}
if(cc && write(fd,buf,cc)<0)
{
cerr<<"Write error"<<endl;
exit(1);
}
}
close(fd);
FD_CLR(fd,&afds);
}
}

buf[MAXLINE]='\0';
Is out of bounds. That may cause any error at any time.
You could declare
char buf[MAXLINE+1]

Related

BrokenPipe error occured in send data in socket programing [duplicate]

This question already has answers here:
What causes the Broken Pipe Error?
(5 answers)
Closed 7 years ago.
I have a client side source code that connects to server over internet.
When I tracing my code it shows me the SIGPIPE error when the compiler run send code. where is my problem?
I changed send method as the comment say and used strcpy.
But I have error again.
#include <QCoreApplication>
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <string> /*To use string type*/
#include <iostream>
#include <string>
#include <QChar>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <typeinfo>//for print the type typeid(a).name --> int
#include <string>
#include <arpa/inet.h>
#include <signal.h>
//#include <pthread.h> //make thread
using namespace std ;
//________________
#define bufsize 100
int sock;
struct sockaddr_in server;
string str;
char* message = new char[bufsize];
char* server_reply = new char[bufsize];
void RECV()
{
memset(&server_reply,'\0',bufsize);
int a=recv(sock , server_reply ,bufsize , 0);
cout<<a;
if(server_reply[0]!='\0')
cout<<server_reply<<endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
sock = socket(AF_INET , SOCK_STREAM , IPPROTO_TCP);//0
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("example.com");//
server.sin_family = AF_UNSPEC;//AF_INET;
server.sin_port = htons( 3490 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
puts("Bienvenido al Chatroom, puedes empezar a escribir en la sala!");
strcpy(message,"Hi");
signal(SIGPIPE, SIG_IGN);
if((send(sock , message , strlen(message)+1 , 0))<0)
{
perror("send");
exit(1);
}
RECV();
close(sock);
return a.exec();
}
In both memset calls, you are passing the address of the pointer rather than the pointer itself. Because bufsize is 100, these memset calls will corrupt other memory. At that point, any number of bad things can happen.
Below is my version of your code that does not get the SIGPIPE. Most notable is that AF_UNSPEC has been changed to AF_INET.
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#define bufsize 100
static int sock;
static char* message = new char[bufsize];
static char* server_reply = new char[bufsize];
static void RECV(int sock)
{
recv(sock, server_reply, bufsize, 0);
printf("%s\n", server_reply);
}
int main(int argc, char *argv[])
{
struct sockaddr_in server;
message = new char[bufsize];
server_reply = new char[bufsize];
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1)
{
printf("Could not create socket");
return 1;
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("93.184.216.34");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
puts("Bienvenido al Chatroom, puedes empezar a escribir en la sala!");
strcpy(message,"GET http://example.com/index.html HTTP/1.1\r\n\r\n");
signal(SIGPIPE, SIG_IGN);
if ((send(sock, message, strlen(message)+1, 0))<0)
{
perror("send");
return 1;
}
puts("Sent\n");
RECV(sock);
close(sock);
return 0;
}

Why i am getting error of adress family not supported by protocol?

I am implementing two way communications using UDP protocol , intitially i send a message HELO from client to server which successfully displays on server side but when i send message from server to client in reply of HELO so it gives me error: Address family not supported by protocol.
Here's my server code:
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
using namespace std;
int main(void)
{
char write[100];
int MAXBUFLEN=100;
char* buf;
char msg[100];
char swp;
int l,x,y;
int conn_sock,n,err;
struct sockaddr_in server_addr,client_addr;
conn_sock=socket(AF_INET,SOCK_DGRAM,0);
if(conn_sock == -1)
{
perror("\n\nError in making socket and error is");
cout<<"Error No:\t\n"<<errno;
exit(0);
}
server_addr.sin_family= AF_INET;
server_addr.sin_port = 1234;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
err=bind(conn_sock,(struct sockaddr *)&server_addr,sizeof(server_addr)); // binding...
if(err == -1)
{
perror("\n\nError in binding and error is:");
cout<<"Error No:\t\n"<<errno;
exit(0);
}
int s=sizeof(client_addr);
n=recvfrom(conn_sock,msg,sizeof(msg),0,(struct sockaddr *)&client_addr,(socklen_t*)s); // reciving HELO from client..
cout<<msg<<endl;
cout<<"The messgae hasbeen recieved from client now enter a reply for HELO msg:"<<endl;
cin>> write;
// sending reply to client
int m=sendto(conn_sock,write,strlen(write),0,(sockaddr *)&client_addr,s); // sending reply to client on reply of helo...
if (m== -1){
perror("talker: sendto");
}
// now recieve mail fromm...
recvfrom(conn_sock,msg,sizeof(msg),0,(struct sockaddr *)&client_addr,(socklen_t*)s);
// sending rcpto client
sendto(conn_sock,write,strlen(write),0,(sockaddr *)&client_addr,s);
recvfrom(conn_sock,msg,sizeof(msg),0,(struct sockaddr *)&client_addr,(socklen_t*)s);
cout<<"Recpt to: Nu.edu.pk"<<endl;
exit(0);
}
And here's my client code:
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#define SERVERPORT "4950" // the port users will be connecting to
#define MAXBUFLEN 100
using namespace std;
int main(int argc, char*argv[])
{
// declarations
char msg3[]="DATA";
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
char buf[MAXBUFLEN];
socklen_t addr_len;
struct sockaddr_storage their_addr;
char* bigarray;
char msg[]="HELO";
char msg2[]="Mail from: Mahnoorfatima#gmail.com";
int i=0;
char * adress;
char * subject;
char * name;
const char *delim="#";
// getting commandline args into arrays.
adress=argv[i+1];
char* host=strtok(adress,delim );
subject=argv[i+2];
name=argv[i+3];
// putting all in one array
bigarray=adress;
bigarray=subject;
bigarray=name;
if(argc>9){
cout << "Just provide three arguments in commandline,please. " << endl;
}
// gets the name of the host:
int a=gethostname(bigarray, 100);
cout<<"The host of the client is:"<<a<<endl;
int conn_sock,n,m,err;
struct sockaddr_in server_addr;
conn_sock=socket(AF_INET,SOCK_DGRAM,0);
if(conn_sock ==-1)
{
perror("\n\nError in making socket and error is");
cout<<"Error No:\t\n"<<errno;
exit(0);
}
server_addr.sin_family= AF_INET;
server_addr.sin_port = 1234;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int pp=sizeof(server_addr);
n=sendto(conn_sock,msg,strlen(msg),0,(sockaddr *)&server_addr,pp);//sending HELO to server...
n=recvfrom(conn_sock,msg,sizeof(msg),0,(struct sockaddr *)&server_addr,(socklen_t*)pp);
cout<<"Mail from: mahnoorfatima22#gmail.com"<<endl;
n=sendto(conn_sock,msg2,strlen(msg2),0,(sockaddr *)&server_addr,pp);
// sending file to server
// reieving from server rcpto command
recvfrom(conn_sock,msg,sizeof(msg),0,(struct sockaddr *)&server_addr,(socklen_t*)pp);
// sending data command to the server....
n=sendto(conn_sock,msg3,strlen(msg3),0,(sockaddr *)&server_addr,pp);
//Sending the filename to server...
if ((n = sendto(sockfd,name,strlen(name), 0,p->ai_addr, p->ai_addrlen)) == -1) {
// perror("Error is sending");
exit(1);
}
// Get the size of the file server sy
addr_len = sizeof their_addr;
if ((n = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,(struct sockaddr *)&their_addr, &addr_len)) == -1) {
// perror("Error in recieving file");
exit(1);
}
cout<<"client: recieved file size: %s\nNumbytes:%d\n"<<buf<<numbytes;
exit(0);
}
The problem is most likely that the recvfrom function expects a pointer to the socket address structure size, while you provide the length by value. That means that the compiler with think that the size you set (sizeof(client_addr)) is interpreted as a pointer, and whatever the structure size is, it's not a valid pointer or pointing to something remotely valid.
That means that the recvfrom might not fill in the peer address structure (client_addr) completely, which leads to your sendto failure.
Try e.g. this instead:
n=recvfrom(conn_sock,msg,sizeof(msg),0,
(struct sockaddr *)&client_addr,&s);
// ^
// |
// Note address-of operator here

Why does the accept() (for socket connections) cause my code to block?

When I run the code it doesn't seem to run the entire main function when this line
connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len);
is in it. It won't even print the first cout at the beginning, but when I comment it out it works fine,can someone tell me the reason for this?
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <iostream>
#define PORT 1227
#define SIM_LENGTH 10;
using namespace std;
void clean_up(int cond, int *sock){
cout<<"exiting";
close(*sock);
exit(cond);
}
int main(void){
cout<<"working;
int sock;
int connect_sock;
struct sockaddr_in serv_name;
size_t len;
int count;
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock<0){
cout<<"Error connecting to socket";
clean_up(1, &sock);
}
bzero(&serv_name, sizeof(serv_name)); // set name as physical address
serv_name.sin_family = AF_INET;
serv_name.sin_port = htons(PORT);
if(bind(sock,(struct sockaddr *)&serv_name, sizeof(serv_name))<0){
cout<<"error naming channel";
clean_up(1, &sock);
}
cout<<"waiting for connection from client";
listen(sock, 1);
len = sizeof(serv_name);
connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len);
cout<<connect_sock;
cout<<"server wrote";
close(connect_sock);
cout<<"connect?";
}
It's waiting for a connection. It doesn't print the first cout because you didn't ask it to. Try:
cout<<"waiting for connection from client"<<endl;

client server programming buffer content not correct

I type two program one for client and one for server.
server is tcp concurrent echo server with select call,in order to use only one process to all client.
it uses apparent concurrency.
I develop program and run its working but after 3/4 message exchange bet client and server.
buffer content at server changes it showing current message with some character from the previous message.
I am not getting why this is happening.
Please anyone able to help me...
//Client Program
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
#define MAXLINE 4096 /*max text line length*/
#define serv_PORT 3000 /*port*/
int main(int argc,char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
char sendline[MAXLINE];
char recvline[MAXLINE];
/*int sendchars,recvchar;
char buf[MAXLINE];
*/
if (argc !=2)
{
cerr<<"Usage: Femto: <IP address of the serv"<<endl;
exit(1);
}
//Create a socket for the client
if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0)
{
cerr<<"Problem in creating the socket"<<endl;
exit(1);
}
//Creation of the socket
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr= inet_addr(argv[1]);
servaddr.sin_port = htons(serv_PORT);
//Connection of the client to the socket
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))<0)
{
cerr<<"Problem in connecting to the serv"<<endl;
exit(1);
}
while (fgets(sendline, MAXLINE, stdin) != NULL)
{
send(sockfd, sendline, strlen(sendline), 0);
if (recv(sockfd, recvline, MAXLINE,0) == 0)
{
cerr<<"The serv terminated"<<endl;
exit(1);
}
cout<< "String received from the serv: ";
fputs(recvline, stdout);
}
exit(0);
}
//Server program
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <sys/select.h>
#include <sys/time.h>
using namespace std;
#define MAXLINE 4096 /*max text line length*/
#define serv_PORT 3000 /*port*/
#define LISTENQ 65535
int main (int argc, char **argv)
{
int msock,ssock;
fd_set rfds;
fd_set afds;
int fd,nfds;
socklen_t client_len ;
char buf[MAXLINE];
struct sockaddr_in clientaddr, servaddr;
if ((msock = socket (AF_INET, SOCK_STREAM, 0)) <0)
{
cerr<<"Problem in creating the socket"<<endl;
exit(1);
}
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(serv_PORT);
bind (msock, (struct sockaddr *) &servaddr, sizeof(servaddr));
listen (msock, LISTENQ);
nfds=getdtablesize();
FD_ZERO(&afds);
FD_SET(msock,&afds);
while(1)
{
memcpy(&rfds,&afds,sizeof(rfds));
if(select(nfds,&rfds,(fd_set *)0,(fd_set *)0,(struct timeval * )0)<0)
{
cerr<<"Error in select";
// exit(1);
}
if(FD_ISSET(msock,&rfds))
{
//int ssock;
ssock= accept(msock,(struct sockaddr *)&clientaddr,&client_len);
if(ssock<0)
{
cerr<<"Accept error";
}
FD_SET(ssock,&afds);
}
int n;
for(fd=0;fd<nfds;++fd)
if(fd!=msock && FD_ISSET (fd,&rfds))
while ( (n = recv(fd, buf, MAXLINE,0)) > 0) {
cout<<"String received from and resent to the client:"<<endl;
puts(buf);
send(fd, buf, n, 0);
}
close(fd);
FD_CLR(fd,&afds);
}
}
output::
client-hi
server-hi
client-bye
server-bye
//after some message exchange
client-wru?
server-wru?
client- i m here
server-i am here u?
You're making the usual mistake of ignoring the count returned by recv(). The data in the buffer is only valid up to that count. The rest of it is unchanged from its previous value.
You're also ignoring the possibility of an error in bind(), listen(), send(), and recv().

C++ TCP Socket Client Fails to Send Data

I am writing a simple socket client in c++. Here is the code:
main.h:
#ifndef CC_Client_main_h
#define CC_Client_main_h
void error(std::string msg);
#endif
main.cpp
#include <iostream>
#include "communications.h"
#include "main.h"
void error(std::string msg) {
std::cerr << msg;
exit(-1);
}
int main(int argc, char **argv) {
Communication communication = Communication("localhost", 8888);
communication.print_hosts();
int success = communication.send_str("hello!\n");
if (success<0) {
std::cerr << "Error writing data.\n";
}
return 0;
}
communications.h
#ifndef __CC_Client__communications__
#define __CC_Client__communications__
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <time.h>
#include <netdb.h>
#include <string>
#include <iostream>
#include main.h
class Communication {
private:
int sock;
struct hostent *host;
struct sockaddr_in server_address;
char *host_str;
int port;
public:
Communication(char *host, int port);
~Communication(void);
hostent &get_host();
void print_hosts(void);
int send_str(char *send_string);
};
#endif /* defined(__CC_Client__communications__) */
communications.cpp
#include "communications.h"
#include "main.h"
void print_addr(unsigned char *address) {
printf("%d.%d.%d.%d\n", address[0], address[1], address[2], address[3]);
}
Communication::Communication(char *host, int port) {
this->port = port;
this->host_str = host;
this->sock = socket(AF_INET, SOCK_STREAM, 0);
if (this->sock<0) {
error("Failed to build socker object.\n");
}
this->host = gethostbyname(host);
if (!this->host) {
error("Failed to resolve host.\n");
}
memset((char*)&this->server_address, 0, sizeof(this->server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port);
memcpy((void *)&this->server_address.sin_addr, this->host->h_addr_list[0], this->host->h_length);
if (connect(this->sock, (struct sockaddr*)&server_address, sizeof(this->server_address))<0) {
error("Failed to connect socket.\n");
}
}
Communication::~Communication() {
std::cout << "Closing connection. . .\n";
shutdown(this->sock, SHUT_RDWR);
std::cout << "Communication object at " << this << " being destroyed\n";
}
void Communication::print_hosts() {
for (int i=0; this->host->h_addr_list[i]!=0; i++) {
print_addr((unsigned char*) this->host->h_addr_list[i]);
}
}
int Communication::send_str(char *send_string) {
char buffer[strlen(send_string)];
int num_bytes = write(this->sock, buffer, sizeof(buffer));
return num_bytes;
}
I tried to use netcat to test the client like this:
$ nc -lv 8888
But the data it receives seems is incorrect:
$ nc -lv 8888
??_?
My program does not give me any errors when I run it. Where is this data coming from?
I am running Mac OS X Mavericks.
you didnt put any data into buffer in send_str
also i suspect that sizeof(buffer) doesn't do what you expect. My guess is that it will be sizeof(char*)