0

I am using this code snippet from an internet website, and according to it, this code works fine. But I'm unable to connect to server. Code and error are given below:

This is the code:

#include <iostream> #include <winsock2.h> #include <string> #include <conio.h> int main() { WSAData version; //We need to check the version. WORD mkword = MAKEWORD(2, 2); int what = WSAStartup(mkword, &version); if (what != 0){ std::cout << "This version is not supported! - \n" << WSAGetLastError() << std::endl; } else{ std::cout << "Good - Everything fine!\n" << std::endl; } SOCKET u_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (u_sock == INVALID_SOCKET) std::cout << "Creating socket fail\n"; else std::cout << "It was okay to create the socket\n"; //Socket address information sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("10.3.34.131"); addr.sin_port = htons(80); /*==========Addressing finished==========*/ //Now we connect int conn = connect(u_sock, (SOCKADDR*)&addr, sizeof(addr)); if (conn == SOCKET_ERROR){ std::cout << "Error - when connecting " << WSAGetLastError() << std::endl; closesocket(u_sock); WSACleanup(); } //Send some message to remote host char* mymsg = "success"; char vect[512] = { 0 }; int smsg = send(u_sock, mymsg, strlen(mymsg), 0); if (smsg == SOCKET_ERROR){ std::cout << "Error: " << WSAGetLastError() << std::endl; WSACleanup(); } int get = recv(u_sock, vect, 512, 0); if (get == SOCKET_ERROR){ std::cout << "Error in Receiving: " << WSAGetLastError() << std::endl; } std::cout << vect << std::endl; closesocket(u_sock); _getch(); return 0; } 

This is the error:

enter image description here How can I correct this error?

4
  • 4
    I'd start by looking both of those error codes up in the winsock error code references. Note the latter is because you cleaned up winsock after the 10061 (connection refused), but then just kept right on marching down your code path as if it was still up and running. Commented Apr 8, 2016 at 5:40
  • Have you checked what's happening on the other side, the server you try to connect to? Commented Apr 8, 2016 at 5:43
  • Also, if you get an error it usually doesn't make sense to continue the program as if nothing happened, especially since you close the socket and call WSACleanup. Commented Apr 8, 2016 at 5:44
  • you have a server running at that ip address that is listening on port 80 ? I don't think so. Commented Apr 9, 2016 at 14:09

1 Answer 1

1

Your network has no machine with IP address 10.3.34.131 that is listening on port 80. Or, if it does, that machine is rejecting your machine's connections to it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.