Error connecting to server by proxy server in c++ socket programming - c++

The code for connection :
cout << "connecting1\n";
WSADATA wsadata;
int iResult = WSAStartup (MAKEWORD(2,2), &wsadata );
if (iResult !=NO_ERROR )
printf("\nmyERROR at WSAStartup()\n");
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("error opening socket"); return -1;
}
struct sockaddr_in sin;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = inet_addr(host.c_str());
sin.sin_family = AF_INET;
if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
perror("error connecting to host"); return -1;
}
const int query_len = query.length() + 1; // trailing '\0'
if (send(sock, query.c_str(), query_len, 0) != query_len) {
perror("error sending query"); return -1;
}
const int buf_size = 1024 * 1024;
while (true) {
std::vector<char> buf(buf_size, '\0');
const int recv_len = recv(sock, &buf[0], buf_size - 1, 0);
if (recv_len == -1) {
perror("error receiving response"); return -1;
} else if (recv_len == 0) {
std::cout << std::endl; break;
} else {
std::cout << &buf[0];
fprintf(fp, "%s", &buf[0]);
}
}
In wifi without proxy it works fine, but when we use proxy server, net can be accessed in chrome, but the above code prints
connecting1
error connecting to host
What is the problem ?

Related

How to receive and parse requests as an HTTP server?

For a class I have to implement an HTTP web server in C++. I currently have the server to the point that it can listen and accept connections, but I can't figure out how to accept data and parse it. When I send a request I get an error saying "Transport endpoint is nt connected." Here's what my code looks like so far:
int main(int argc, char *argv[]) {
// parse CLI args
if (argc != 3) { /** change to 3 once DOCROOT is added */
cout << "invalid arguments" << endl;
exit(1);
}
const char *DOCROOT = argv[1];
const char *PORT = argv[2];
// declare vars....from beej's so some not in use yet
int sockfd, new_fd;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr;
socklen_t sin_size;
struct sigaction sa;
int yes = 1;
char s[INET6_ADDRSTRLEN];
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
// try getaddrinfo
if ((rv = getaddrinfo(nullptr, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through getaddrinfo response and bind when possible
for (p=servinfo; p!=nullptr; p=p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (::bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("server: bind");
continue;
}
break;
}
freeaddrinfo(servinfo);
if (p == nullptr) {
fprintf(stderr, "server: failed to bind\n");
exit(1);
}
/** choose backlog number and declare constant */
if (listen(sockfd, 5) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, nullptr) == -1) {
perror("sigaction");
exit(1);
}
printf("server: waiting for connections on port %s...\n", PORT);
while(true) { /** this will be the main accept loop */
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
// receive
char recvbuf[1024];
int recvbuflen = 1024;
int request = recv(sockfd, recvbuf, recvbuflen, 0);
if (request == -1) perror("error receiving data");
if(send(new_fd, "Data received", 15, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
return 0;
}

HTTP GET request using C++ WinSock, Binance API

I'm trying first to connect with Binance api endpoint which is /api/v3/ping.
However I'm getting "HTTP/1.1 400 Bad Request" response, what should be updated in this code?
int main()
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char buffer[BUFFERSIZE];
std::string request;
std::cout<<("Initialising Winsock...\n");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
std::cout<<("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
std::cout<<("Initialised.\n");
if ((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
std::cout << ("Could not create socket : %d", WSAGetLastError());
}
std::cout << ("Socket created.\n");
const wchar_t* IP = _T("52.84.198.235");
InetPton(AF_INET, IP, &server.sin_addr.s_addr);
server.sin_family = AF_INET;
server.sin_port = htons(443);
if (connect(s, (struct sockaddr*)&server, sizeof(server)) < 0)
{
std::cout<<("connect error\n");
return 1;
}
std::cout<<("Connected\n");
request += "GET /api/v3/ping HTTP/1.1\r\nHost: api.binance.com\r\n\r\n";
if (send(s, request.c_str(), strlen(request.c_str()), 0) < 0)
{
std::cout<<("Send failed\n");
return 1;
}
std::cout << ("Data Send\n");
std::string response;
int resp_leng;
response = "";
resp_leng = BUFFERSIZE;
while (resp_leng)
{
resp_leng = recv(s, (char*)&buffer, BUFFERSIZE, 0);
if (resp_leng > 0)
response += std::string(buffer).substr(0, resp_leng);
}
std::cout << response << "\n";
closesocket(s);
WSACleanup();
return 0;
}
I was using info from a few sites and stackoverflow questions, I'm wondering if it can be about SSL?

Server only receiving null string from client? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I have a basic client/server c++ program. Right now, when the client connects to the server I want the server sends a "Hello, world" message and the client to respond "Hello, server" just to make sure I am sending and relieving messages correctly.
When I run, the client receives the message from the server, but the server only receives a null string from the client.
Here is the code for the client
int main(int argc, char *argv[]) {
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr,"usage: client hostname\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return 2;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
s, sizeof s);
printf("client: connecting to %s\n", s);
freeaddrinfo(servinfo); // all done with this structure
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
if (send(sockfd, "Hello, client!", 13, 0) == -1) {
perror("send");
}
buf[numbytes] = '\0';
printf("client: received '%s'\n",buf);
close(sockfd);
return 0;
}
and Here's the code for the server
int main(void)
{
int sockfd, new_fd, numbytes; // listen on sock_fd, new connection on new_fd
char buf[MAXDATASIZE];
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
struct sigaction sa;
int yes=1;
char s[INET6_ADDRSTRLEN];
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("server: bind");
continue;
}
break;
}
freeaddrinfo(servinfo); // all done with this structure
if (p == NULL) {
fprintf(stderr, "server: failed to bind\n");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
printf("server: waiting for connections...\n");
while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
if (send(new_fd, "Hello, world!", 13, 0) == -1)
perror("send");
if (numbytes = recv(new_fd, &buf, MAXDATASIZE-1, 0) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("server: received '%s'\n",buf);
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
return 0;
}
Now I figured it out:
if (numbytes = recv(new_fd, &buf, MAXDATASIZE-1, 0) == -1) {
recv(new_fd, &buf, MAXDATASIZE-1, 0) == -1 is 0 on success and 1 on error. And that gets assigned to numbytes. So, you want to add parenthesises like this:
if ((numbytes = recv(new_fd, &buf, MAXDATASIZE-1, 0)) == -1) {
Or you want to split it into two lines like this:
numbytes = recv(new_fd, &buf, MAXDATASIZE-1, 0);
if (numbytes == -1) {
Oh and next time plz decide for either C or C++, both are different languages.

error in send data to server

Why when run the program and send data to server return this errorrecv failed: Transport endpoint is not connected or don't show server accepted just show the message of send data function in client
server.cpp:
int main() {
char packet[30];
char buffer[20] = "I got your message";
int conn_sock, comm_sock, n, m;
struct sockaddr_in server_addr, client_addr;
if ((conn_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Couldn't create socket");
exit(1);
}
cout << "Already create socket!!!\n" << endl;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(0);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(&server_addr, 0, sizeof(server_addr));
if (bind(conn_sock, (struct sockaddr *) &server_addr, sizeof(server_addr))
== -1) {
perror("couldn't bind");
exit(1);
}
if (listen(conn_sock, 10) == -1) {
perror("couldn't listen");
exit(1);
}
cout << "Listening For Connection...\r" << endl;
socklen_t len = sizeof(server_addr);
if (getsockname(conn_sock, (struct sockaddr *) &server_addr, &len) == -1)
perror("getsockname");
else
printf("port number %d\n", ntohs(server_addr.sin_port));
while (1) {
memset(&client_addr, 0, sizeof(client_addr));
if ((comm_sock = accept(conn_sock, (struct sockaddr *) &client_addr,
(socklen_t *) &client_addr)) == -1) {
perror("couldn't accept\n");
continue;
}
cout << "accepted" << endl;
bzero(packet, 10);
m = recv(conn_sock, packet, 10, 0);
if (m < 0) {
perror("recv failed");
exit(1);
}
cout<<"recieved"<<endl;
/* Write a response to the client */
n = send(conn_sock, buffer, sizeof(buffer), 0);
if (n < 0) {
perror("ERROR send to client");
exit(1);
}
close(n);
close(m);
close(comm_sock);
}
close(conn_sock);
return 0;
}
cilent.cpp:
#define MYPORT 51833
namespace personalization {
bool client::conn() {
//create socket if it is not already created
if (sock == -1) {
//Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("Could not create socket");
}
cout << "Socket created" << endl;
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(MYPORT);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sock , (struct sockaddr *)&server_addr , sizeof(server_addr)) < 0)
{
perror("connect failed. Error");
return false;
}
cout<<"Connected\n";
return true;
close(sock);
}
bool client::send_data() {
//Send some data
if( send(sock , packet , sizeof( packet ) , 0) < 0)
{
perror("Send failed");
return false;
}
cout<<"Data send\n";
return true;
close(sock);
}
bool client::rec_data() {
char buffer[20];
string reply;
//Receive a echo from the server
if (recv(sock, buffer, sizeof(buffer), 0) < 0) {
perror("receive failed");
return false;
}
reply = buffer;
return true;
close(sock);
}
client::client() {
// TODO Auto-generated constructor stub
sock=-1;
}
output is:
server:Already create socket!!!
Listening For Connection...
port number 51833
client: Socket created
Connected
Data send
receive failed: Connection reset by peer
or:
server:Already create socket!!!
Listening For Connection...
port number 51833
client:Socket created
Connected
Data send
srver:accepted
recv failed: Transport endpoint is not connected
In the server's recv and send calls, you need to pass the socket returned from accept.
So instead of
m = recv(conn_sock, packet, 10, 0);
do
m = recv(comm_sock, packet, 10, 0);
Same goes for the send call.
Also, don't call close on n and m, that is to say remove these two lines of code:
close(n);
close(m);
EDIT: Sorry, while I'm at it, this is probably not what you intended in the client's send_data and rec_data:
return true;
close(sock);

C++ cant receive UDP-Packets (Socket)

I am working on a C++ UDP program, that sends a string to another client and should receive an answer.
Sending works fine, but i cant receive any packets. I looked with wireshark and my computer receives the packet at the right port and from the right IP, but my program seems to ignore them.
Do you have any idea?
int startWinsock(void);
int main()
{
long receive;
SOCKET sock;
char buffer[256];
SOCKADDR_IN si_me;
SOCKADDR_IN si_other;
///////////// Start Winsock ///////////////
receive = startWinsock();
if (receive != 0)
{
printf("Error: startWinsock, error code: %d\n", receive);
return 1;
}
else
{
printf("Winsock started!\n");
}
//////////// Create UDP Socket //////////////
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET)
{
printf("Fehler: Socket could not be created, errorcode: %d\n", WSAGetLastError());
return 1;
}
else
{
printf("UDP Socket created!\n");
}
si_me.sin_family = AF_INET;
si_me.sin_port = htons(1198);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
si_other.sin_family = AF_INET;
si_other.sin_port = htons(2000);
si_other.sin_addr.s_addr = inet_addr("10.2.134.10");
receive = connect(sock, (SOCKADDR*)&si_other, sizeof(SOCKADDR));
if (receive == SOCKET_ERROR)
{
cout << "Error : Connection Failed, Errorcode: " << WSAGetLastError() << endl;
}
else
{
cout << "Connected to" << si_other.sin_addr.s_addr << endl;
}
static int timeout = 500;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
// char broadcast = 1;
// setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
while (1)
{
printf("Insert Text: ");
gets(buffer);
//rc = sendto(s, buf, strlen(buf), 0, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN));
receive = send(sock, buffer, strlen(buffer), 0);
if (receive == SOCKET_ERROR)
{
//printf("error: sendto, error code: %d\n",WSAGetLastError());
printf("Error: send, error code: %d\n", WSAGetLastError());
//return 1;
}
else
{
printf("%d bytes sent!\n", receive);
}
static int timeout = 500;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
int wait = 0;
while (wait == 0)
{
//rc = recvfrom(s, buf, 256, 0, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN));
receive = recv(sock, buffer, sizeof(buffer), 0);
if (receive == SOCKET_ERROR)
{
//printf("Fehler: recvfrom, fehler code: %d\n",WSAGetLastError());
printf("Fehler: recv, fehler code: %d\n", WSAGetLastError());
//return 1;
}
else
{
wait = 1;
printf("%d bytes received!\n", receive);
buffer[receive] = '\0';
printf("Received: %s\n", buffer);
}
}
}
getchar();
return 0;
}
int startWinsock(void)
{
WSADATA wsa;
return WSAStartup(MAKEWORD(2, 0), &wsa);
}
To make it so your code works nearly as-is by sending to itself, do the following:
change the "me" port to match "other"... si_me.sin_port = htons( 2000 );
bind to it... bind( sock, (SOCKADDR*)&si_me, sizeof( SOCKADDR ) ); just before connect
As UDP is Datagram-Oriented and connectionless, you need to use recvfrom/sento instead of recv/send. Also the receivetimeout should be set with at timeval.
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));