I want to understand more about sending data over internet.
I have been searching A LOT everywhere but nothing helped...
I'm using MinGw and please dont say that i have to change my developer program.
So far i made this from what I found:
And it work great but only for my local network. Can anyone tell me how i can do the same thing only over the internet?
using namespace std;
#pragma once
#include <iostream>
#include "WinSock2.h"
const int STRLEN = 256;
class Socket
{
protected:
WSADATA wsaData;
SOCKET mySocket;
SOCKET myBackup;
SOCKET acceptSocket;
sockaddr_in myAddress;
public:
Socket();
~Socket();
bool SendData( char* );
bool RecvData( char*, int );
void CloseConnection();
void GetAndSendMessage();
};
class ServerSocket : public Socket
{
public:
void Listen();
void Bind( int port );
void StartHosting( int port );
};
class ClientSocket : public Socket
{
public:
void ConnectToServer( const char *ipAddress, int port );
};
Socket::Socket()
{
if( WSAStartup( MAKEWORD(2, 2), &wsaData ) != NO_ERROR )
{
cerr<<"Socket Initialization: Error with WSAStartup\n";
system("pause");
WSACleanup();
exit(10);
}
//Create a socket
mySocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( mySocket == INVALID_SOCKET )
{
cerr<<"Socket Initialization: Error creating socket"<<endl;
system("pause");
WSACleanup();
exit(11);
}
myBackup = mySocket;
}
Socket::~Socket()
{
WSACleanup();
}
bool Socket::SendData( char *buffer )
{
send( mySocket, buffer, strlen( buffer ), 0 );
return true;
}
bool Socket::RecvData( char *buffer, int size )
{
int i = recv( mySocket, buffer, size, 0 );
buffer[i] = '\0';
return true;
}
void Socket::CloseConnection()
{
//cout<<"CLOSE CONNECTION"<<endl;
closesocket( mySocket );
mySocket = myBackup;
}
void Socket::GetAndSendMessage()
{
char message[STRLEN];
cin.ignore();//without this, it gets the return char from the last cin and ignores the following one!
cout<<"Send > ";
cin.get( message, STRLEN );
SendData( message );
}
void ServerSocket::StartHosting( int port )
{
Bind( port );
Listen();
}
void ServerSocket::Listen()
{
//cout<<"LISTEN FOR CLIENT..."<<endl;
if ( listen ( mySocket, 1 ) == SOCKET_ERROR )
{
cerr<<"ServerSocket: Error listening on socket\n";
system("pause");
WSACleanup();
exit(15);
}
//cout<<"ACCEPT CONNECTION..."<<endl;
acceptSocket = accept( myBackup, NULL, NULL );
while ( acceptSocket == SOCKET_ERROR )
{
acceptSocket = accept( myBackup, NULL, NULL );
}
mySocket = acceptSocket;
}
void ServerSocket::Bind( int port )
{
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr( "0.0.0.0" );
myAddress.sin_port = htons( port );
//cout<<"BIND TO PORT "<<port<<endl;
if ( bind ( mySocket, (SOCKADDR*) &myAddress, sizeof( myAddress) ) == SOCKET_ERROR )
{
cerr<<"ServerSocket: Failed to connect\n";
system("pause");
WSACleanup();
exit(14);
}
}
void ClientSocket::ConnectToServer( const char *ipAddress, int port )
{
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr( ipAddress );
myAddress.sin_port = htons( port );
//cout<<"CONNECTED"<<endl;
if ( connect( mySocket, (SOCKADDR*) &myAddress, sizeof( myAddress ) ) == SOCKET_ERROR )
{
cerr<<"ClientSocket: Failed to connect\n";
system("pause");
WSACleanup();
exit(13);
}
}
int main()
{
int choice;
int port = 666;
//char *ipAddress = "127.0.0.1";
string ipAddress;
bool done = false;
char recMessage[STRLEN];
char sendMessage[STRLEN];
cout<<"1) Host server"<<endl;
cout<<"2) Join server"<<endl;
cout<<"3) Quit"<<endl;
cin>>choice;
if ( choice == 3 )
exit(0);
else if ( choice == 2 )
{
//Client
cout<<"Enter an IP address, 127.0.0.1 is the loopback address"<<endl;
cin>>ipAddress;
ClientSocket sockClient;
cout<<"ATTEMPTING TO CONNECT..."<<endl;
sockClient.ConnectToServer( ipAddress.c_str(), port );
//Connected
while ( !done )
{
sockClient.GetAndSendMessage();
cout<<"\t--WAIT--"<<endl;
sockClient.RecvData( recMessage, STRLEN );
cout<<"Recv > "<<recMessage<<endl;
if ( strcmp( recMessage, "end" ) == 0 ||
strcmp( sendMessage, "end" ) == 0 )
{
done = true;
}
}
sockClient.CloseConnection();
}
else if ( choice == 1 )
{
//SERVER
ServerSocket sockServer;
cout<<"HOSTING..."<<endl;
sockServer.StartHosting( port );
//sockServer.StartHosting( port );
//Connected
while ( !done )
{
cout<<"\t--WAIT--"<<endl;
sockServer.RecvData( recMessage, STRLEN );
cout<<"Recv > "<<recMessage<<endl;
sockServer.GetAndSendMessage();
if ( strcmp( recMessage, "end" ) == 0 || strcmp( sendMessage, "end" ) == 0 )
{
done = true;
}
}
}
}
Thanks to all who responded but, you gave me a lot to read when i just asked what part of the code should be changed so i can use the internet. Obviously I cant understand half of what is written there. Still nothing helped.
If you want to use sockets over the internet and you want your application to be usable on every network setting, including NAT, you will have to use a TCP Holepunch called technique (or UDP holepunching may also fit). I think your approach is not working
because there is some NAT between your endpoints, so socket connections fail.
I suggest to investigate on NAT. Peer-to-Peer Communication Across Network Address Translators
And this discussion here on SO
What is it that you don't understand? I see the code and it's binding to a local socket and then you connect to it with a client. You can do this over the internet as well but what is it that you aren't understanding about the process? I'm afraid you may need to start learning the basics of TCP/IP before trying to write socket code. It's like trying to start out learning engineering by building a space shuttle.
The ability to host a service that's visible from the Internet is very dependent on the type of the Internet connection you've got. If you're behind a NAT, you'll need to set up a NAT port forwarding. If your IP address is dynamic, you'll need to know your publicly available IP address (try http://www.whatismyip.com/).
Related
I have written code in C++ with Winsock. It converts a video to mjpeg stream and sends it over TCP using Winsock in windows. Now I am able to see the video in any browser with the link.
But the problem is that anyone with the link can see it. I want to prompt the user to enter username and password to access the feed, whenever he types the IP address.
Here is my code:
#include <winsock.h>
#include <windows.h>
#include <time.h>
#define PORT unsigned long
#define ADDRPOINTER int*
struct _INIT_W32DATA
{
WSADATA w;
_INIT_W32DATA() { WSAStartup( MAKEWORD( 2, 1 ), &w ); }
} _init_once;
#include <iostream>
using std::cerr;
using std::endl;
#include <iostream>
#pragma comment(lib, "wsock32.lib")
using namespace std;
class MJPGWriter
{
SOCKET sock;
fd_set master;
int timeout; // master sock timeout, shutdown after timeout millis.
int quality; // jpeg compression [1..100]
int _write( int sock, char *s, int len )
{
if ( len < 1 ) { len = strlen(s); }
return ::send( sock, s, len, 0 );
}
public:
MJPGWriter(int port = 0)
: sock(INVALID_SOCKET)
, timeout(20000)
, quality(30)
{
FD_ZERO( &master );
if (port)
open(port);
}
~MJPGWriter()
{
release();
}
bool release()
{
if ( sock != INVALID_SOCKET )
::shutdown( sock, 2 );
sock = (INVALID_SOCKET);
return false;
}
bool open( int port )
{
sock = ::socket (AF_INET, SOCK_STREAM, IPPROTO_TCP) ;
SOCKADDR_IN address;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_family = AF_INET;
address.sin_port = ::htons(port);
if ( ::bind( sock, (SOCKADDR*) &address, sizeof(SOCKADDR_IN) ) == SOCKET_ERROR )
{
cerr << "error : couldn't bind sock "<<sock<<" to port "<<port<<"!" << endl;
return release();
}
if ( ::listen( sock, 10 ) == SOCKET_ERROR )
{
cerr << "error : couldn't listen on sock "<<sock<<" on port "<<port<<" !" << endl;
return release();
}
FD_SET( sock, &master );
return true;
}
bool isOpened()
{
return sock != INVALID_SOCKET;
}
bool write(const cv::Mat & frame)
{
fd_set rread = master;
struct timeval to = {0,timeout};
SOCKET maxfd = sock+1;
if ( ::select( maxfd, &rread, NULL, NULL, &to ) <= 0 )
return true; // nothing broken, there's just noone listening
std::vector<uchar>outbuf;
std::vector<int> params;
params.push_back(cv::IMWRITE_JPEG_QUALITY);
params.push_back(quality);
cv::imencode(".jpg", frame, outbuf, params);
int outlen = outbuf.size();
#ifdef _WIN32
for ( unsigned i=0; i<rread.fd_count; i++ )
{
SOCKET s = rread.fd_array[i]; // fd_set on win is an array, while ...
#else
for ( int s=0; s<maxfd; s++ )
{
if ( ! FD_ISSET(s,&rread) ) // ... on linux it's a bitmask ;)
continue;
#endif
if ( s == sock ) // request on master socket, accept and send main header.
{
int addrlen = sizeof(SOCKADDR);
SOCKADDR_IN address = {0};
SOCKET client = ::accept( sock, (SOCKADDR*)&address, &addrlen );
if ( client == SOCKET_ERROR )
{
cerr << "error : couldn't accept connection on sock " << sock<< " !" << endl;
return false;
}
maxfd=(maxfd>client?maxfd:client);
FD_SET( client, &master );
_write( client,"HTTP/1.0 200 OK\r\n",0);
_write( client,
"Server: Mozarella/2.2\r\n"
"Accept-Range: bytes\r\n"
"Connection: close\r\n"
"Max-Age: 0\r\n"
"Expires: 0\r\n"
"Cache-Control: no-cache, private\r\n"
"Pragma: no-cache\r\n"
"Content-Type: multipart/x-mixed-replace; boundary=mjpegstream\r\n"
"\r\n",0);
cerr << "new client " << client << endl;
}
else // existing client, just stream pix
{
char head[400];
sprintf(head,"--mjpegstream\r\nContent-Type: image/jpeg\r\nContent-Length: %lu\r\n\r\n",outlen);
_write(s,head,0);
int n = _write(s,(char*)(&outbuf[0]),outlen);
//cerr << "known client " << s << " " << n << endl;
if ( n < outlen )
{
cerr << "kill client " << s << endl;
::shutdown(s,2);
FD_CLR(s,&master);
}
}
}
return true;
}
};
I am using it by sending image frame and port number to writer.
I am trying to implement a simple UDP broadcaster and listener on two PCs running Windows 10 64 Pro (1803). I have come across numerous c/c++ examples but I cannot get any of them to work on my local net.
I set up a receiver PC on my local net at 192.168.0.1 and a sender PC at 192.168.0.2 with subnet masks 255.255.255.0 and use the local broadcast address of 192.168.0.255.
They do work when used on the same machine with localhost, MS loopback adapter and any local adapter I might choose. They also work with two machines connected to a wifi router with a gateway. They just don't seem to work with a regular basic switch, which is what I need. I can see the messages coming in on the listener PC using Wireshark but my listener code (recvfrom()) does not respond. If tried disabling the Windows firewall but that has no effect.
*One interesting thing. If I have the listener code up, and send a broadcast from that listener PC, the listener code WILL respond to that and to subsequent broadcasts from the broadcaster PC while in the while loop. If I exit and restart, its the same nonresponsive result as before.*
This code that follows is one of many I have tried but they're all basically the same handful of operations.
Example sender code:
#include <winsock2.h>
#include <iostream>
#include <conio.h>
using namespace std;
#define MYPORT 9009 // the port users will be connecting to
int main()
{
WSADATA wsaData;
WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
SOCKET sock;
sock = socket( AF_INET, SOCK_DGRAM, 0 );
char broadcast = '1';
if ( setsockopt( sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast) ) < 0 )
{
cout<<"Error in setting Broadcast option";
closesocket(sock);
return 0;
}
struct sockaddr_in Recv_addr;
struct sockaddr_in Sender_addr;
int len = sizeof( struct sockaddr_in );
char sendMSG[] ="Attention: this is a broadcast!!!";
char recvbuff[50] = "";
int recvbufflen = 50;
Recv_addr.sin_family = AF_INET;
Recv_addr.sin_port = htons( MYPORT );
Recv_addr.sin_addr.s_addr = inet_addr( "192.168.0.255" ); // switch doesnt work
// Recv_addr.sin_addr.s_addr = inet_addr( "192.168.1.255" ); //wifi router works
cout << "sending message: " << sendMSG;
sendto( sock, sendMSG, (int) strlen(sendMSG)+1, 0,(sockaddr*) &Recv_addr, sizeof( Recv_addr ) );
closesocket( sock );
WSACleanup();
}
Example receiver code:
#include "winsock2.h"
#include <iostream>
#include <conio.h>
using namespace std;
#define MYPORT 9009 // the port users will be connecting to
int main()
{
WSADATA wsaData;
WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
SOCKET sock;
sock = socket( AF_INET, SOCK_DGRAM, 0 );
char broadcast = '1';
// This option is needed on the socket in order to be able to receive broadcast messages
// If not set the receiver will not receive broadcast messages in the local network.
if ( setsockopt( sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof( broadcast ) ) < 0 )
{
cout<<"Error in setting Broadcast option";
closesocket(sock);
return 0;
}
struct sockaddr_in Recv_addr;
struct sockaddr_in Sender_addr;
int len = sizeof( struct sockaddr_in );
char recvbuff[50];
int recvbufflen = 50;
Recv_addr.sin_family = AF_INET;
Recv_addr.sin_port = htons( MYPORT );
Recv_addr.sin_addr.s_addr = INADDR_ANY;
if ( bind( sock, (sockaddr*) &Recv_addr, sizeof (Recv_addr) ) < 0 )
{
cout << "Error in BINDING" << WSAGetLastError();
_getch();
closesocket(sock);
return 0;
}
do
{
cout << "\nWaiting for message...\n";
recvfrom( sock, recvbuff, recvbufflen, 0, (sockaddr*) &Sender_addr, &len );
cout << "Received Message is: " << recvbuff;
} while ( 1 );
closesocket(sock);
WSACleanup();
}
Issues:
1) To close down the server say after 10 sec if request to accept connection has not come from client.
2) Also broke the connection and close the server if no packets has been received from the client say for 10 secs .
Overview : I have an application which opens RFcomm server connection and DUT( Device under test) connects to it. Once connection with Rfcomm has been established then the application creates SCO server and listen for sco connection. All I wanted is to close the server if no request for conncection has been received on RFcomm or SCO side . Also close the connection and server if DUT has failed to send any packets with 10 secs.
As pointed out by forum member to me to use KEEPALIVE but my application crashes as I think KEEPALIVE does not work with SOL_SCO.
Below are the sample code
int ScoServerListen(void( *handler )( int sco_listen_sock ) )
{
printf(" start sco_listen connection\n" );
struct sockaddr_sco addr;
struct sco_conninfo conn;
socklen_t optlen;
int sco_listen_sock, sco_accept_sock;
char ba[18];
int *new_sock;
// Create socket //
sco_listen_sock = socket( PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO );
if( sco_listen_sock < 0 )
{
printf( "Can't create socket: %s (%d)\n", strerror( errno ), errno );
exit(1);
}
printf(" start sco_listen connection .. socket created.... yeeee \n" );
// Bind to local address //
memset( &addr, 0, sizeof( addr ) );
addr.sco_family = AF_BLUETOOTH;
bacpy( &addr.sco_bdaddr, &bdaddr );
if( bind( sco_listen_sock, ( struct sockaddr * ) &addr, sizeof( addr ) ) < 0)
{
printf("Can't bind socket: %s (%d)\n", strerror(errno), errno );
goto error;
}
printf(" start sco_listen connection .. bind done.... yeeee \n" );
// Listen for connections //
if( listen( sco_listen_sock, no_of_connect_listen ) )
{
printf("Can not listen on the socket: %s (%d)\n", strerror( errno ), errno );
goto error;
}
std::cout << "Waiting for connection ...\n";
while( 1 )
{
memset(&addr, 0, sizeof(addr));
optlen = sizeof(addr);
sco_accept_sock = accept( sco_listen_sock, ( struct sockaddr * ) &addr, &optlen );
if( sco_accept_sock < 0 )
{
printf("Accept for SCO failed: %s (%d)\n", strerror( errno ), errno );
goto error;
}
//using socketoption
//Get connection information //
memset( &conn, 0, sizeof( conn ) );
optlen = sizeof( conn );
if( getsockopt( sco_accept_sock, SOL_SCO, SCO_CONNINFO, &conn, &optlen ) < 0)
{
printf( "Can't get SCO connection information: %s (%d)\n", strerror(errno), errno);
close( sco_accept_sock );
goto error;
}
ba2str( &addr.sco_bdaddr, ba );
printf( "Connect from %s [handle %d, class 0x%02x%02x%02x]",ba, conn.hci_handle, conn.dev_class[2], conn.dev_class[1], conn.dev_class[0]);
pthread_t sniffer_thread;
new_sock = (int*)malloc(1);
*new_sock = sco_accept_sock;
if( pthread_create( &sniffer_thread, NULL, connection_handler, (void*)new_sock )< 0 )
{
perror(" could not create thread");
return 1;
}
( void )pthread_join( sniffer_thread, NULL );
puts (" handler assigned");
close( sco_accept_sock );
close( sco_listen_sock );
printf( "Disconnect");
//close( sco_listen_sock );
exit(0);
}
return 0;
error:
close( sco_listen_sock );
exit( 1 );
}
void *connection_handler( void *socket_desc)
{
// get socket descriptor
int sock = *(int*)socket_desc;
int read_size;
char*message, message_client[ 200 ];
//receive messgae from client
while( read_size = recv( sock, message_client, 200, 0 ) > 0 )
{
printf(" very good\n");
}
if( read_size == 0 )
{
printf("clinet disconnected \n");
fflush( stdout);
}
else if( read_size == -1 )
{
printf("received failed \n");
perror( " recv fialed");
}
free( socket_desc );
int rel = 200;
pthread_exit(&rel);
return 0;
}
int RfcommListen( uint8_t channel )
{
printf(" rfcomm --> we are at that start\n");
int rfcomm_sock; // socket descriptor for local listener
int rfcomm_client; // socket descriptor for remote client
socklen_t len = sizeof(struct sockaddr_rc);
struct sockaddr_rc remote; // local rfcomm socket address
struct sockaddr_rc local; // remote rfcomm socket address
char pszremote[20]={ 0 };
// initialize a bluetooth socket
rfcomm_sock = socket( PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM );
if( rfcomm_sock < 0 )
{
printf( "RFComm socket Error \n" );
return BtSocketError;
}
memset(&local, 0, sizeof(local));
local.rc_family = AF_BLUETOOTH;
local.rc_bdaddr = *BDADDR_ANY_INITIALIZER;
local.rc_channel = channel;
// bind the socket to a bluetooth device
if( bind( rfcomm_sock, ( struct sockaddr * )&local, sizeof( local ) ) < 0 )
{
close( rfcomm_sock );
return BtSocketError;
}
printf(" rfcomm --> bind successful\n");
// set the listening queue length
if( listen( rfcomm_sock, 1 ) < 0 )
{
printf(" we are in SCO Configure where listen failed \n");
return BtSocketError;
}
printf("accepting connections on channel: %d\n", channel);
// accept incoming connections; this is a blocking call
rfcomm_client = accept( rfcomm_sock, (struct sockaddr *)&remote, &len );
ba2str( &remote.rc_bdaddr, pszremote );
printf("received connection from: %s\n", pszremote);
// turn off blocking
if ( fcntl( rfcomm_client, F_SETFL, O_NONBLOCK ) < 0 )
{
printf("Failed non blocking\n");
return BtSocketError;
}
// return the client socket descriptor
return rfcomm_client;
}
I wrote this module for a chat room, and whenever the socket dies it should try to reconnect. However, I've noticed that after around 10 or 15 minutes, the socket will stop trying to reconnect. Why could this happen? My code is as follows:
bool Socket::Connection::_connect(int delay_ms)
{
closesocket(sock);
hostEntry = gethostbyname(host);
if( !hostEntry )
{
//Couldn't resolve our host
return false;
}
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if( sock == INVALID_SOCKET )
{
//Invalid socket
return false;
}
SOCKADDR_IN serverInfo;
serverInfo.sin_family = AF_INET;
serverInfo.sin_addr = *(LPIN_ADDR)*hostEntry->h_addr_list;
serverInfo.sin_port = htons(port);
int nret = SOCKET_ERROR;
while( (nret == SOCKET_ERROR) )
{
nret = connect(sock, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr));
if( nret == SOCKET_ERROR )
Sleep(delay_ms);
if( running == false )
return false;
}
return true;
}
void Socket::Connection::start()
{
u_long iMode = 1;
fd_set rdevents;
struct timeval tv;
while( 1 ) //Outer, connection loop
{
if( !_connect(RECONNECT_TIME) )
continue;
int nret = ioctlsocket(sock, FIONBIO, &iMode);
if( nret != NO_ERROR )
continue;
//if( onconnect != NULL )
//onconnect(sock);
while( 1 ) //Inner, command loop
{
FD_ZERO( &rdevents );
FD_SET( sock, &rdevents );
tv.tv_sec = 8;
tv.tv_usec = 0;
nret = select(0, &rdevents, NULL, NULL, &tv);
if( nret == SOCKET_ERROR )
{
break;
}
else if( nret > 0 )
{
if( FD_ISSET(sock, &rdevents) )
{
char buf[1024];
nret = recv(sock, buf, 1024, 0);
if( nret == 0 )
break;
if( onrecv != NULL ) onrecv(sock, buf, nret);
}
}
}
}
closesocket(sock);
}
I fail to see the code where it says 'if socket dies, reconnect'. I do see the code that says 'when I ask you to connect, try connection in a loop till that succeeds'. They are two different things. Is there something else somewhere in your code that keeps calling start() in a loop? The command loop in the start() function would be 'breaking' out on socket errors .... and I do not see any attempt to reconnect after that break out.
#include <sys/socket.h> // for socket(), bind(), listen(), accept()
#include <netinet/in.h> // for PF_INET, SOCK_STREAM, IPPROTO_TCP
#include <stdio.h> // for printf(), perror()
#include <unistd.h> // for read(), write(), close()
#include <string.h> // for bzero()
#define DEMO_PORT 9723
int main( void )
{
//-----------------------------------------
// create an unnamed socket for the server
//-----------------------------------------
int sock = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( sock < 0 )
{
perror( "opening stream socket" );
return -1;
}
printf( "\nsock=%d \n", sock );
//----------------------------------------
// construct a name for the server socket
//----------------------------------------
struct sockaddr_in self;
socklen_t nlen = sizeof self;
bzero( &self, sizeof self );
self.sin_family = AF_INET;
self.sin_port = htons( DEMO_PORT );
self.sin_addr.s_addr = htonl( INADDR_ANY );
if ( bind( sock, (sockaddr *)&self, nlen ) < 0 )
{
perror( "bind failed" );
return -1;
}
printf( "bind succeeded port: %d\n",DEMO_PORT);
//---------------------------------------------------------
// now create a connection queue and wait for some clients
//---------------------------------------------------------
if ( listen( sock, 5 ) < 0 )
{
perror( "listen failed" );
return -1;
}
printf( "listen succeeded \n" );
//---------------------------------------------------
// main loop to process clients' connection-requests
//---------------------------------------------------
while ( 1 )
{
sockaddr_in peer;
socklen_t plen = sizeof peer;
bzero( &peer, plen );
printf( "server waiting \n" );
int client = accept( sock, (sockaddr *)&peer, &plen );
if ( client < 0 ) { perror( "accept" ); break; }
//---------------------------------------------
// we can now read from or write to the client
//---------------------------------------------
char ch;
int index = 0;
char get[1024];
if ( read( client, &ch, 1 ) < 0 )
{
perror( "read" );
}
bool go = true;
while(go){
if(ch != '/' && ch != '\r'){
printf("read: %hhd\n", ch);
get[index] = ch;
printf( "got stuff: %s\n", get );
index++;
read(index, &ch, 1);
} else {
go = false;
index = 0;
close( client );
printf( "server responded, connection closed" );
}
}
//if ( write( client, &ch, 1 ) < 0 ) { perror( "write" ); break; }
}
close( sock );
printf( "\n" );
}
the while(go) look never works and it buffers incorrectly. I do not see the pattern within the buffer or how it works.
What is the correct way to do this? to except a certain amount of bytes, store them in a string, then terminate the read if it reaches a newline character?
You are passing index into the second read call where you should be passing client.
This may not be your only problem but I think it is one of them.