I implented a socket client to communicate to an ip camera with RTSP over HTTP to get teh video from the camera.
To stablished the communication with the camera, first i have to set an HTTP-GET tunnel, then send the RTSP commands. When the camera loses the connection, the program has to close the tunnel handler, finish the thread and when the process return to the main function, it begins the communication (start the treads, and so on).
On the reconnection: the http-get tunnel is set ok, i mean, the socket connects and receives a "HTTP OK", so the program sends a RTSP "DESCRIBE" but the recv always return an EAGAIN error. I check with wireshar that the DESCRIBE OK response is sent from the camera, but the recv never gets it.
Here is the code:
struct sockaddr_in aServer;
// string myData;
char *myData=new char [256];
connection *c=(connection*)vargp;
memset(&aServer, 0, sizeof aServer);
aServer.sin_family = AF_INET;
aServer.sin_addr.s_addr = inet_addr(c->theServer.c_str());
if (aServer.sin_addr.s_addr == INADDR_NONE)
{
struct hostent *hp;
hp = gethostbyname(c->theServer.c_str());
if (hp != NULL)
{
memcpy(&aServer.sin_addr, hp->h_addr, hp->h_length);
aServer.sin_family = hp->h_addrtype; //Protocol family
}
else
cout << "Failed to resolve " << c->theServer.c_str() << ": " << hstrerror(h_errno) << endl;
}
aServer.sin_port = htons(c->thePort);
c->fd_get = socket(AF_INET, SOCK_STREAM, 0);
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
setsockopt(c->fd_get, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
if (c->fd_get < 0){
cout << "fd_get < 0" << endl;
c->bFin=true;
c->WakeUP();
}
if (connect(c->fd_get, (struct sockaddr *) &aServer, sizeof aServer) < 0){
cout << "connect fd_get < 0" << endl;
c->bFin=true;
c->WakeUP();
}
if(!c->bFin){
sprintf(myData, "GET %s HTTP/1.1\r\n", c->theURI.c_str());
sprintf(myData, "%sx-sessioncookie: %s\r\nAccept: application/x-rtsp-tunnelled\r\nAuthorization: %s\r\n\r\n", myData,c->theHTTPSessionId.c_str(), c->addAuthorization(c->aGlobalUsername, c->aGlobalPassword).c_str() );
cout << myData << endl;
write(c->fd_get, myData, strlen(myData));
//LISTENING...
int theLen=1500; //3000;
int ret=0;
unsigned char datosRecibidos[3000];
int flags =fctl(c->fd_get, F_GETFD;
if((flags & O_NONBLOCK) == O_NONBLOCK){
fprint(stderr, "yup, its nonblocking");
}
else{
fprint(stderr, "nope, its blocking");
}
while (c->bFin==false){
ret = read(c->fd_get, ReceivedData, theLen);
// ret= recvfrom(c->fd_get, ReceivedData, theLen, 0, (struct sockaddr *) 0, (socklen_t*)0);
if (ret == 0)
{
cout << "Server closed connection: 0" << endl;
}
else
if (ret == -1){
fprintf (stderr, "\n[%d]: %s %d\n", __LINE__, strerror (errno), errno);
if(errno==107 ||errno==EAGAIN){
cout << "errno" << endl;
c->bFin=true;
c->WakeUP();
cout << "vuelta wakeUP" << endl;
break;// empezar de nuevo
}else{
cout << "errno" << endl;
}
}
else{
//cout << (string)ReceivedData[0]<< endl;
c->ProcessReceivedData(ReceivedData, ret);
usleep(10);
}
}
close(c->fd_get);
c->fd_get = -1;
}
Could it be a timeout problem? or a stack problem? How can i solve it?
Thanks in advance for your help. Best regards.
cristina
EAGAIN means there is no data available for reading on a non-blocking socket. So, you should run the recv call again.
You haven't actually posted enough code to suggest there is a programming fault, although can I ask if when you detect the connection is closed that you also close down your end as well before re-establishing everything?
Is your socket open in O_NONBLOCK mode? You can check like this:
int flags = fcntl(fd, F_GETFD);
if ((flags & O_NONBLOCK) == O_NONBLOCK) {
fprintf(stderr, "Yup, it's nonblocking");
}
else {
fprintf(stderr, "Nope, it's blocking.");
}
In nonblocking mode, recv will return immediately with errno set to EAGAIN if there is nothing to receive yet.
I would always use poll() or select() before going for each socket read operation.
Also to test for NON-Blocking:
int flags = fcntl(fd, F_GETFL, 0);
if (flags & O_NONBLOCK) {
fprintf(stderr, "Yup, it's nonblocking");
} else {
fprintf(stderr, "Nope, it's blocking.");
}
Related
I created a small app on small router with 4 LAN ports. Router has been flashed with OpenWrt system, Linux kernel 5.4.154
Devices connected to LAN ports are sending date over TCP POSTs. The app is listening on specified TCP port and sends data to the server or stores it in SD card. Everything work fine until someone will start playing with plugs on the LAN side. Somethings is happening and app hangs in accept() function waiting for incomming data.
I assume (please correct me if I'm wrong) system changes?/resets? port routing and data are not delivered to the app socket any more.
Is there a simple solution to keep the 'subscription' of TCP port?
I've tried to rewrite app in async mode, but not everything is working correctly, is this the only solution for this problem?
Below simpyfied working(!) code in blocking mode (I removed all unnecesary stuff, so it may not compile)
int main() {
// Create server_socket as socket
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
cerr << "Can't create a socket! Quitting" << endl;
}
int enable = 1;
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
{
cout << GetTime() << "Can't use SO_REUSEADDR" << endl;
}
while (true) {
// Bind the ip address and port to a socket
listenningport = 55555;
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(listenningport);
inet_pton(AF_INET, "0.0.0.0", &hint.sin_addr);
if (bind(server_socket, (sockaddr*) &hint, sizeof(hint)) == -1) {
cerr << "Can't bind to IP/port" << endl;
}
// Tell Winsock the socket is for server_socket
if (listen(server_socket, SOMAXCONN) == -1) // handle multiconnections SOMAXCONN(4096, queue)
{
cerr << "Can't listen!" << endl;
}
// Wait for a connection
sockaddr_in client;
socklen_t clientSize = sizeof(client);
while (true) {
// Waiting for data on socket; block mode
int clientSocket = accept(server_socket, (sockaddr*) &client, &clientSize);
if (clientSocket == -1) {
cerr << "Problem with client connecting!" << endl;
// break the loop and try to renew socket connection
break;
}
else {
// receive all data till the end of message
int bytesReceived = 0;
while ((bytesReceived = recv(readSocket, out_data + msgSize, maxSizeOutData - msgSize - 1, 0)) > 0) {
msgSize += bytesReceived;
if (msgSize > maxSizeOutData + 1)
break;
}
// no data received
if (bytesReceived == -1) {
cerr << "Error in recv(). BytesReceived = -1" << endl;
}
close(clientSocket);
}
}
}
My aim is to write C++ program which receives data from network using udp protocol. OS - linux. I have few questions.
I want to make sure that I can use linux C libraries to write C++ program.
Is anywhere exists full tutorial which expailns step by step how to program using sockets in linux? ( I know that in network is many tutorials, but I'm looking for something which help me receive udp data from INTERNET, not from another program on the same device.).
I see in terminal ( using tcpdump) that my computer receive udp packages addressed to specified port. What's wrong with my program which looks like this
class Connection
{
private:
char * buffer;
int bufferSize;
int sock;
struct sockaddr_in server;
struct sockaddr_in other;
socklen_t addressLength;
public:
Connection(string address, int port, int bufferSize);
~Connection();
int reciveData();
};
Connection::Connection(string address, int port, int bufferSize)
{
this->addressLength = sizeof(this->server);
this->sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(this->sock == -1)
{
cout << "Socket error!" << endl;
exit(1);
}
memset(&(this->server), 0, sizeof(this->server));
this->server.sin_family = AF_INET;
this->server.sin_port = htons(port);
this->server.sin_addr.s_addr = htonl(INADDR_ANY);
if( bind(this->sock, (sockaddr *) &(this->server), this->addressLength) == -1 )
{
cout << "Bind socket error!" << endl;
exit(1);
}
this->bufferSize = bufferSize;
this->buffer = new char[bufferSize];
cout << "Socket created!" << endl;
}
int Connection::receiveData()
{
int returned;
fflush(stdout);
if( (returned =recvfrom(this->sock, this->buffer, this->bufferSize, 0, (sockaddr *) &(this->other), &this->addressLength)) == -1)
{
cout << "Receiving error!" << endl;
exit(1);
}
return returned;
}
When i call receiveData() nothing's happening - I think program waits for some udp package ( and i don't know why he does not receive it).
Could someone explain me difference between udp server and client program ?
Thanks a lot.
When calling recvfrom(), you are passing it a pointer to this->addressLength. On input, the length needs to be the complete size of the address buffer. On output, the actual address length is returned. So recvfrom() might be altering your addressLength member, affecting subsequent code. Use a local variable instead:
int Connection::receiveData()
{
int returned;
int addrlen = sizeof(this->other);
fflush(stdout);
returned = recvfrom(this->sock, this->buffer, this->bufferSize, 0, (sockaddr *) &(this->other), &addrLen);
if( returned == -1 )
{
cout << "Receiving error!" << endl;
exit(1);
}
return returned;
}
Alternatively, use a separate member variable instead:
class Connection
{
private:
char * buffer;
int bufferSize;
int sock;
struct sockaddr_in server;
struct sockaddr_in other;
socklen_t serverAddressLength;
socklen_t otherAddressLength;
public:
Connection(string address, int port, int bufferSize);
~Connection();
int reciveData();
};
Connection::Connection(string address, int port, int bufferSize)
{
this->serverAddressLength = sizeof(this->server);
this->sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(this->sock == -1)
{
cout << "Socket error!" << endl;
exit(1);
}
if(this->sock == -1)
{
cout << "Socket error!" << endl;
exit(1);
}
memset(&(this->server), 0, sizeof(this->server));
this->server.sin_family = AF_INET;
this->server.sin_port = htons(port);
this->server.sin_addr.s_addr = htonl(INADDR_ANY);
if( bind(this->sock, (sockaddr *) &(this->server), this->serverAddressLength) == -1 )
{
cout << "Bind socket error!" << endl;
exit(1);
}
this->bufferSize = bufferSize;
this->buffer = new char[bufferSize];
cout << "Socket created!" << endl;
}
int Connection::receiveData()
{
int returned;
fflush(stdout);
this->otherAddressLength = sizeof(this->other);
if( (returned =recvfrom(this->sock, this->buffer, this->bufferSize, 0, (sockaddr *) &(this->other), &this->otherAddressLength)) == -1)
{
cout << "Receiving error!" << endl;
exit(1);
}
return returned;
}
I am currently programming a C++ module that creates a socket server thread, which polls the accept() function every 1ms. I have a test module that spoofs a client connection that is also running. The test module initiates the creation of the server thread. After the thread is created and verified to be running, the client runs the connect() command as a test. My code states that a connection was established, returning a 0 on the connect command. However, the accept() running in my server thread never receives the connection.
The server is bound to accepting any IP:50000, and the client is not bound, but has 127.0.0.1:50000 set as its destination. Is my Linux environment automatically accepting this connection?
Here is the code for my server's socket:
int nSocket;
int nOn = 1;
int nControl;
struct sockaddr_in sServerAddress;
nSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(nSocket < 0)
{
std::cout << "Failed to create socket\n";
}
if(setsockopt(nSocket, SOL_SOCKET, SO_REUSEADDR, &nOn, sizeof(int)) < 0)
{
std::cout << "failed to set socket option\n";
}
nControl = fcntl(nSocket, F_GETFL);
if(fcntl(nSocket, F_SETFL, O_NONBLOCK | nControl) < 0)
{
std::cout << "set not blocking failed\n";
}
memset(&sServerAddress, 0x00, sizeof(struct sockaddr_in));
sServerAddress.sin_family = AF_INET;
sServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
sServerAddress.sin_port = htons(mtListenPort);
if(bind(nSocket, (struct sockaddr*)&sServerAddress, sizeof(struct sockaddr_in)) < 0)
{
std::cout << errno << "bind failed\n";
}
if(listen(nSocket, MAXPENDING) < 0)
{
std::cout << "listen failed\n";
}
Here is the code for my test client's socket:
int nSocket;
nSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(nSocket < 0)
{
std::cout << "Failed to create socket\n";
}
struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
inet_aton(LOCAL_HOST, &serverAddress.sin_addr);
serverAddress.sin_port = htons(LISTEN_PORT00);
char msg[] = "Hello World.";
usleep(10000);
if (connect(nSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0)
{
std::cout << errno << "Could not connect to the server.\n";
}
usleep(10000);
if (sendto(nSocket, msg, strlen(msg), 0, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0)
{
std::cout << errno << "Could not send data to the server.\n";
}
Here is a small part of the thread that runs the accept code.
while(mbListening)
{
nMessengerSocket = accept(mnSocket, (struct sockaddr*)&sClientAddr, &tClientAddrLength);
if(nMessengerSocket >= 0)
{
std::cout << "Accepted connection from " << inet_ntoa(sClientAddr.sin_addr) << std::endl;
mnConnections++;
mbListening = false;
}
mThreadRunningTime++;
usleep(1000);
}
Make sure tClientAddrLength is initialized to sizeof sClientAddr before calling accept(). That is a common error.
Don't silently ignore errors. Examine the error code in errno because it tells you what went wrong.
Are you using sendto? That's for UDP... Use send.
Also, check if the port is free:
telnet localhost 50000
netstat -a
I'm making a server, client app in c++ console based.
What I did so far:
I can connect to the server.
I can send messages to the server.
The server can send the messages back.
But what I can't figure out, how can I let the server act also as a client to send messages to the client while he is processing received messages from the client?
People can use it as an example as well :D
Well I will post also some parts of the code:
server:
#include "stdafx.h"
using namespace std;
//our main function
void main()
{
int numClients;
long antwoord;
char chatname[100];
char bericht[250]; //messages
char sbericht[250]; //smessages
//here we set the Winsock-DLL to start
WSAData wsaData;
WORD DLLVERSION;
DLLVERSION = MAKEWORD(2,1);
//here the Winsock-DLL will be started with WSAStartup
//version of the DLL
antwoord = WSAStartup(DLLVERSION, &wsaData);
if(antwoord != 0)
{
WSACleanup();
exit(1);
}
else
{
cout << "WSA started successfully" <<endl;
cout << "The status: \n" << wsaData.szSystemStatus <<endl;
}
//the DLL is started
//structure of our socket is being created
SOCKADDR_IN addr;
//addr is our struct
int addrlen = sizeof(addr);
//socket sListen - will listen to incoming connections
SOCKET sListen;
//socket sConnect - will be operating if a connection is found.
SOCKET sConnect;
//setup of our sockets
//opgezocht op internet - AF_INET bekend dat het lid is van de internet familie
//Sock_STREAM betekenend dat onze socket een verbinding georiƫnteerde socket is.
sConnect = socket(AF_INET,SOCK_STREAM,NULL);
//now we have setup our struct
//inet_addr is our IP adres of our socket(it will be the localhost ip
//that will be 127.0.0.1
addr.sin_addr.s_addr = inet_addr("192.168.1.103");
//retype of the family
addr.sin_family = AF_INET;
//now the server has the ip(127.0.0.1)
//and the port number (4444)
addr.sin_port = htons(4444);
//here we will define the setup for the sListen-socket
sListen = socket(AF_INET,SOCK_STREAM,NULL);
if (sConnect == INVALID_SOCKET)
{
cout << "Error at socket(): \n" << WSAGetLastError() <<endl;
WSACleanup();
}
else
{
cout << "Connect socket() is OK!" <<endl;
}
if(sListen == INVALID_SOCKET)
{
cout << "Error at socket(): \n" << WSAGetLastError() <<endl;
WSACleanup();
}
else
{
cout << "Listen socket() is OK!" <<endl;
}
//here the sListen-socket will be bind
//we say that the socket has the IP adress of (127.0.0.1) and is on port (4444)
//we let the socket become the struct "addr"
if(bind(sListen, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR)
{
cout << "bind() failed: \n" << WSAGetLastError() <<endl;
WSACleanup();
exit(1);
}
else{
cout << "bind() is OK!" <<endl;
}
//here we will tell what the server must do when a connection is found
//therefor we will create an endless loop
cout << "Waiting for a incoming connection..." <<endl;
for(;;)
{
//now we let the socket listen for incoming connections
//SOMAXCOMM heeft het nut dat het dan voordurend luisterd naar inkomende verbindingen zonder limiet
listen(sListen, SOMAXCONN);
while(numClients < SOMAXCONN)
{
//if a connection is found: show the message!
if(sConnect = accept(sListen, (SOCKADDR*)&addr, &addrlen))
{
cout << "A Connection was found!" <<endl;
antwoord = send(sConnect, "Welcome to our chat:", 21,NULL);
if(antwoord > 1)
{
antwoord = recv(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = recv(sConnect, chatname, sizeof(chatname), NULL);
while(antwoord = recv(sConnect, sbericht, sizeof(sbericht), NULL) && (antwoord = recv(sConnect, sbericht, sizeof(sbericht), NULL)) )
{
antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = send(sConnect, chatname, sizeof(chatname), NULL);
}
}
else
{
cout << "The connection to the client has been lost... \n" << "please exit the server." <<endl;
break;
}
numClients++;
}
}
}
}
Client:
// ChatServer.cpp : Defines the entry point for the console application.
//
//include of the stdafx.h file where importent files are being included
#include "stdafx.h"
using namespace std;
void smessage()
{
}
//our main function
int main()
{
//here we set the Winsock-DLL to start
string bevestiging;
char chatname[100];
char bericht[250];
char sbericht[250];
string strbericht;
string strsbericht;
long antwoord;
//here the Winsock-DLL will be started with WSAStartup
//version of the DLL
WSAData wsaData;
WORD DLLVERSION;
DLLVERSION = MAKEWORD(2,1);
antwoord = WSAStartup(DLLVERSION, &wsaData);
if(antwoord != 0)
{
exit(1);
}
else
{
cout << "WSA started successfully" <<endl;
cout << "The status: \n" << wsaData.szSystemStatus <<endl;
}
SOCKADDR_IN addr;
int addrlen = sizeof(addr);
SOCKET sConnect;
sConnect = socket(AF_INET, SOCK_STREAM, NULL);
if (sConnect == INVALID_SOCKET)
{
cout << "Error at socket(): \n" << WSAGetLastError() <<endl;
}
else
{
cout << "socket() is OK!\n" <<endl;
}
addr.sin_addr.s_addr = inet_addr("192.168.1.103");
addr.sin_family = AF_INET;
addr.sin_port = htons(4444);
cout << "What is your chat name?" <<endl;
cin.getline(chatname, 100);
cout << "Do you want to connect to the server? [Y/N]" <<endl;
cin >> bevestiging;
if (bevestiging == "N")
{
exit(1);
}
else
{
if(bevestiging == "Y")
{
connect(sConnect, (SOCKADDR*)&addr, sizeof(addr));
antwoord = recv(sConnect, bericht, sizeof(bericht), NULL);
strbericht = bericht;
cout << strbericht << chatname <<endl;
while(true)
{
if(antwoord > 1)
{
cin.clear();
cin.sync();
cout << chatname << " :" <<endl;
cin.getline(sbericht, 250);
antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = send(sConnect, chatname, sizeof(chatname), NULL);
while(antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL) && (antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL)))
{
antwoord = recv(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = recv(sConnect, chatname, sizeof(chatname), NULL);
cout << chatname << ":" <<endl;
cout << sbericht <<endl;
cin.getline(sbericht, 250);
}
}
else
{
cout << "The connection to the server has been lost... \n" << "please exit the client." <<endl;
}
}
}
}
}
You would probably have to open another socket. The client would have to act as a server as well.
First of all: putting a 20mb zip file in to the web for about 4 interesting source files is not a good option. Your object files and debug output is of no interest to us, since we want to help with your source code. Try uploading a zip file containing only the source files the next time.
Secondly: If others want to understand your source code and are not familiar with your native language, they have to guess. Try using english as source code language for this and a variety of other reasons.
Now to answer your question:
The answer is already in your code. Currently, the server is looping until a maximum number of connects, receives input and sends back an answer. So actually you have already implemented it. I guess if you want to send initiated messages in both ways you have to alter your software architecture a bit.
Your code has a few fundamental problems:
The server can only handle one client at a time. If your server will ever have more than a single user on it (as a chat server invariably will), you need to be able to listen for more than one connection at once. select, or WSAEventSelect and WaitForMultipleObjects, would help a lot here.
You assume that a whole fixed-size message will appear at a time. TCP can not guarantee that (as the "stream" concept considers the data as just a potentially infinite sequence of individual bytes), and a half-sent message could freeze up your server while it waits for the rest. Not a big deal if this is all on your LAN, but if you expose this service to the internet, you're asking for random lockups. In order to prevent that, get the data and put it in a buffer as it comes, processing it only when you have a whole message.
The conversation is done in lock-step. That is, the client sends a message, and waits for a response, and then (and only then) expects console input. With this design, there will always be one message received per message sent. In order to get around this, i'll often have a thread for the data going in each direction -- one that gets the console input and sends it to the server, while the other listens to the server and prints the message received. (Note, this means messages could be received while you're typing. That's kinda the point. But it makes console input a bit annoying.) Threading is a semi-advanced topic -- once you start creating new threads, you often have to worry about synchronization and such. But it's generally cleaner than the alternatives in this case.
Sample threaded code (very roughly, since i don't have a C++ compiler handy):
const int MessageLength = 250;
const int NameLength = 250;
char myname[NameLength];
bool sendFully(SOCKET s, char* buffer, size_t buffer_len, int flags)
{
char *end = buffer + buffer_len;
while (buffer != buffer_len)
{
int sent = send(s, buffer, end - buffer, flags);
if (sent == 0) return false;
buffer += sent;
}
return true;
}
DWORD WINAPI watchConsoleInput(void*)
{
char input[MessageLength];
while (true)
{
std::cin.getline(input, MessageLength);
if (!sendFully(sConnect, input, sizeof(input), 0))
break;
if (!sendFully(sConnect, myname, sizeof(myname), 0))
break;
}
return 0;
}
int main()
{
char chatname[NameLength];
char sbericht[MessageLength];
... get our name in myname ...
... do the connect stuff ...
HANDLE watcher = CreateThread(NULL, 0, watchConsoleInput, NULL, 0, NULL);
while (true)
{
// Added MSG_WAITALL to work around the whole-message-at-a-time thing
if (recv(sConnect, sbericht, sizeof(sbericht), MSG_WAITALL) != sizeof(sbericht))
break;
if (recv(sConnect, chatname, sizeof(chatname), MSG_WAITALL) != sizeof(sbericht))
break;
}
// Don't care about errors; we're just being polite
shutdown(sConnect, SD_BOTH);
closesocket(sConnect);
cout << "Connection lost\n";
// ExitProcess rather than just 'return', so we know the watcher thread dies
ExitProcess(0);
}
Hey guys, here is my code.
int main() {
char buffer[BUFSIZE];
// define our address structure, stores our port
// and our ip address, and the socket type, etc..
struct sockaddr_in addrinfo;
addrinfo.sin_family = AF_INET;
addrinfo.sin_port = htons(PORT);
addrinfo.sin_addr.s_addr = INADDR_ANY;
// create our socket.
int sock;
if ( (sock = socket(addrinfo.sin_family, SOCK_STREAM, 0)) < 0) {
cout << "Error in creating the socket.";
}
// bind our socket to the actual adress we want
if (bind(sock, (struct sockaddr*)&addrinfo, sizeof(addrinfo)) != 0) {
cout << "Error in binding.";
}
// open the socket up for listening
if (listen(sock, 5) != 0) {
cout << "Error in opening listener.";
}
cout << "Waiting for connections...." << endl;
char *msg = "Success! You are connected.\r\n";
// continuously accept new connections.. but no multithreading.. yet
while(1) {
struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(client_addr);
if(int client = accept(sock, (struct sockaddr*)&client_addr, &sin_size)) {
cout << "Recived new connection from " << inet_ntoa(client_addr.sin_addr) << endl;
send(client, msg, strlen(msg), 0);
while(1) {
send(client, buffer, recv(client, buffer, BUFSIZE, 0), 0);
cout << buffer << endl;
strcpy(buffer, "");
}
} else {
cout << "Error in accepting new connection." << endl;
}
}
close(sock);
return 0;
}
Now, I'm very new to sockets, Im just sort of trying to get a feel for them but I do have some experience with sockets in PHP. I'm using telnet via putty on my linux machine to test this, I don't know if thats causing any issues but the server is outputting some strange characters and I don't know why. I think it has something to do with the buffer, but I'm not really sure. I can send things like "hi" to the server via telnet and it outputs them just fine and sends them back to me but when I send things like "hoobla" it starts the funky character stuff. Any suggestions would be helpful!
Thanks in advance!
You're getting rubbish printed out because recv does not null-terminate your buffer.
The important section in the below code is:
int num = recv(client,buffer,BUFSIZE,0);
if (num < 1) break;
send(client, ">> ", 3, 0); // <<-- Nice to have.
send(client, buffer, num, 0);
buffer[num] = '\0'; // <<-- Really important bit!
if (buffer[num-1] == '\n') // <<-- Nice to have.
buffer[num-1] = '\0'; // <<-- Nice to have.
cout << buffer << endl;
which will properly terminate your buffer before trying to print it, as well as remove the trailing newline if present (and allow the client to distinguish between input and echoed lines).
This one (a complete program) works a little better:
using namespace std;
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUFSIZE 1000
#define PORT 1234
int main() {
char buffer[BUFSIZE];
// define our address structure, stores our port
// and our ip address, and the socket type, etc..
struct sockaddr_in addrinfo;
addrinfo.sin_family = AF_INET;
addrinfo.sin_port = htons(PORT);
addrinfo.sin_addr.s_addr = INADDR_ANY;
// create our socket.
int sock;
if ( (sock = socket(addrinfo.sin_family, SOCK_STREAM, 0)) < 0) {
cout << "Error in creating the socket.";
return -1;
}
// bind our socket to the actual adress we want
if (bind(sock, (struct sockaddr*)&addrinfo, sizeof(addrinfo)) != 0) {
cout << "Error in binding.";
return -1;
}
// open the socket up for listening
if (listen(sock, 5) != 0) {
cout << "Error in opening listener.";
return -1;
}
char *msg = "Success! You are connected.\r\n";
// continuously accept new connections.. but no multithreading.. yet
while(1) {
cout << "Waiting for connections...." << endl;
struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(client_addr);
if(int client =
accept(sock, (struct sockaddr*)&client_addr, &sin_size))
{
cout << "Recieved new connection from "
<< inet_ntoa(client_addr.sin_addr) << endl;
send(client, msg, strlen(msg), 0);
while(1) {
int num = recv(client,buffer,BUFSIZE,0);
if (num < 1) break;
send(client, ">> ", 3, 0);
send(client, buffer, num, 0);
buffer[num] = '\0';
if (buffer[num-1] == '\n')
buffer[num-1] = '\0';
cout << buffer << endl;
strcpy(buffer, "");
}
} else {
cout << "Error in accepting new connection." << endl;
}
}
close(sock);
return 0;
}
On the client side:
$ telnet 127.0.0.1 1234
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Success! You are connected.
hello
>> hello
my name is pax
>> my name is pax
and you?
>> and you?
<CTRL-D>
Connection closed by foreign host.
and, on the server side:
$ ./testprog
Waiting for connections....
Recived new connection from 127.0.0.1
hello
my name is pax
and you?
Waiting for connections....
The problem is that buffer is not guaranteed to contain a string-terminating null character. Add the line buffer[BUFSIZE-1] = '\0' just before your cout << buffer.
Even better, actually record how many bytes were received, and use that information to determine if you overran your buffer.