I'm writing a simple program about TCP Socket. What I'm going to do is send whatever 1000 data structure from client to server, but it display segmentation fault....
This is my server:
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
using namespace std;
#pragma pack(1)
struct student
{
int id;
string name;
};
main()
{
struct sockaddr_in socketInfo;
socklen_t fromlen;
int socketHandle;
int portNumber = 8080;
bzero(&socketInfo, sizeof(sockaddr_in)); // Clear structure memory
// create socket
if((socketHandle = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
close(socketHandle);
exit(EXIT_FAILURE);
}
// Load system information into socket data structures
socketInfo.sin_family = AF_INET; //IPv4
socketInfo.sin_addr.s_addr = htonl(INADDR_ANY); // Use any address available to the system
socketInfo.sin_port = htons(portNumber); // Set port number
// Bind the socket to a local socket address
if( bind(socketHandle, (struct sockaddr *) &socketInfo, sizeof(socketInfo)) < 0)
{
close(socketHandle);
perror("bind");
exit(EXIT_FAILURE);
}
listen(socketHandle, 1);
int socketConnection;
while(1)
{
cout<<"Waiting to connect ..."<<endl;
if( (socketConnection = accept(socketHandle, NULL, NULL)) < 0)
{
cout<<"Fail!!"<<endl;
exit(EXIT_FAILURE);
}
//close(socketHandle);
int rc = 0; // Actual number of bytes read
struct student buf;
while(1)
{
rc = recv(socketConnection, &buf, sizeof(struct student)+1, 0);
cout<<"Recieve = "<<rc<<endl;
if (rc<=0)
break;
cout<<buf.id<<endl;
cout<<buf.name<<endl;
}
}
}
This is my client:
#include <iostream>
#include <sstream>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
unsigned long inet_addr(const string a);
string int2str( int val ) // interger convert to string
{
ostringstream out;
out<<val;
return out.str();
}
#pragma pack(1)
struct student
{
int id;
string name;
};
main()
{
struct sockaddr_in remoteSocketInfo;
struct hostent *hPtr;
const char *remoteHost="localhost";
int socketHandle;
int portNumber = 8080;
bzero(&remoteSocketInfo, sizeof(sockaddr_in)); // Clear structure memory
if((hPtr = gethostbyname(remoteHost)) == NULL)
{
cerr << "System DNS name resolution not configured properly." << endl;
cerr << "Error number: " << ECONNREFUSED << endl;
exit(EXIT_FAILURE);
}
if((socketHandle = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
close(socketHandle);
exit(EXIT_FAILURE);
}
// Load system information into socket data structures
memcpy((char *)&remoteSocketInfo.sin_addr, hPtr->h_addr, hPtr->h_length);
remoteSocketInfo.sin_family = AF_INET;
remoteSocketInfo.sin_port = htons(portNumber); // Set port number
if(connect(socketHandle, (struct sockaddr *)&remoteSocketInfo, sizeof(sockaddr_in)) < 0)
{
close(socketHandle);
exit(EXIT_FAILURE);
}
struct student buf[1000];
for (int i=0; i<1000; i++)
{
buf[i].id = i+1;
buf[i].name = "student_" + int2str(i) + "00";
send(socketHandle, &buf[i], sizeof(struct student)+1, 0);
}
}
Result:
Waiting to connect ...
Recieve = 13
1
Segmentation fault (core dumped)
The problem here is that one of the fields in struct student is a std::string object. This can't be sent across the wire directly like you're doing.
Instead, either change it to a fixed-size character array something like this...
struct student
{
int id;
char name[100];
}
... and write your name into there. Or you'll have to send it across the wire in a different way.
Related
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
I would like to send a string: "Jane Doe" to intranet ip 192.168.0.4 to port 9000 over UDP. I have done this many times via UDP and TCP by Java, but now I have to do it with standard C++ libraries and I can't find any samples only topics where people just can't make it work.
I know that I have to encode "Jane Doe" as array of bytes then just open socket, pack it in datagram and send it.
C++ is not my first language and this is small part of code I can't figure out, I've chosen UDP because it is always much simpler than TCP.
A good source for network programming is Beej's Guide to Network Programming. Below is some sample Unix code.
If this is Windows programming:
"sock" should be of type SOCKET instead of int.
Use closesocket instead of close
#include <winsock2.h> instead of all those unix headers
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <memory.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <errno.h>
#include <stdlib.h>
#include <iostream>
int resolvehelper(const char* hostname, int family, const char* service, sockaddr_storage* pAddr)
{
int result;
addrinfo* result_list = NULL;
addrinfo hints = {};
hints.ai_family = family;
hints.ai_socktype = SOCK_DGRAM; // without this flag, getaddrinfo will return 3x the number of addresses (one for each socket type).
result = getaddrinfo(hostname, service, &hints, &result_list);
if (result == 0)
{
//ASSERT(result_list->ai_addrlen <= sizeof(sockaddr_in));
memcpy(pAddr, result_list->ai_addr, result_list->ai_addrlen);
freeaddrinfo(result_list);
}
return result;
}
int main()
{
int result = 0;
int sock = socket(AF_INET, SOCK_DGRAM, 0);
char szIP[100];
sockaddr_in addrListen = {}; // zero-int, sin_port is 0, which picks a random port for bind.
addrListen.sin_family = AF_INET;
result = bind(sock, (sockaddr*)&addrListen, sizeof(addrListen));
if (result == -1)
{
int lasterror = errno;
std::cout << "error: " << lasterror;
exit(1);
}
sockaddr_storage addrDest = {};
result = resolvehelper("192.168.0.4", AF_INET, "9000", &addrDest);
if (result != 0)
{
int lasterror = errno;
std::cout << "error: " << lasterror;
exit(1);
}
const char* msg = "Jane Doe";
size_t msg_length = strlen(msg);
result = sendto(sock, msg, msg_length, 0, (sockaddr*)&addrDest, sizeof(addrDest));
std::cout << result << " bytes sent" << std::endl;
return 0;
}
This is very easy to do if you are willing to use the boost library.
Here is the code snippit
#include "boost/asio.hpp"
using namespace boost::asio;
...
io_service io_service;
ip::udp::socket socket(io_service);
ip::udp::endpoint remote_endpoint;
socket.open(ip::udp::v4());
remote_endpoint = ip::udp::endpoint(ip::address::from_string("192.168.0.4"), 9000);
boost::system::error_code err;
socket.send_to(buffer("Jane Doe", 8), remote_endpoint, 0, err);
socket.close();
I rewrote selbie's code to make it more C++-like and I minimized it a bit.
#include <iostream>
#include <string>
#include <arpa/inet.h> // htons, inet_addr
#include <netinet/in.h> // sockaddr_in
#include <sys/types.h> // uint16_t
#include <sys/socket.h> // socket, sendto
#include <unistd.h> // close
int main(int argc, char const *argv[])
{
std::string hostname{"192.168.0.4"};
uint16_t port = 9000;
int sock = ::socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in destination;
destination.sin_family = AF_INET;
destination.sin_port = htons(port);
destination.sin_addr.s_addr = inet_addr(hostname.c_str());
std::string msg = "Jane Doe";
int n_bytes = ::sendto(sock, msg.c_str(), msg.length(), 0, reinterpret_cast<sockaddr*>(&destination), sizeof(destination));
std::cout << n_bytes << " bytes sent" << std::endl;
::close(sock);
return 0;
}
For Windows, I took Mikolasan's minimised version of selbie's code and modified according to https://beej.us/guide/bgnet/html/#windows to get a small standalone example.
To get this to compile, you'll need to link the Winsock library.
#include <iostream>
#include <string>
#include <winsock2.h>
int main()
{
// Initialise Winsock DLL
// See https://beej.us/guide/bgnet/html/#windows
WSADATA wsaData;
// MAKEWORD(1,1) for Winsock 1.1, MAKEWORD(2,0) for Winsock 2.0
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
fprintf(stderr, "WSAStartup failed.\n");
exit(1);
}
// Set up connection and send
std::string hostname{ "192.168.0.4" };
uint16_t port = 9000;
SOCKET sock = ::socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in destination;
destination.sin_family = AF_INET;
destination.sin_port = htons(port);
destination.sin_addr.s_addr = inet_addr(hostname.c_str());
std::string msg = "Jane Doe";
int n_bytes = ::sendto(sock, msg.c_str(), msg.length(), 0, reinterpret_cast<sockaddr*>(&destination), sizeof(destination));
std::cout << n_bytes << " bytes sent" << std::endl;
::closesocket(sock);
// Clean up sockets library
WSACleanup();
return 0;
}
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().
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*)
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]