M
M
mercy_smile2021-06-05 21:50:50
C++ / C#
mercy_smile, 2021-06-05 21:50:50

What is the error in the code?

int a()
{
  WSADATA wsa;
  std::string domin;
  int status;
  struct addrinfo hints = { 0 }, * res, * p;
  hints.ai_family = AF_INET; 
  hints.ai_socktype = SOCK_STREAM;

  SetConsoleCP(GetACP());
  SetConsoleOutputCP(GetACP());

  if (status = WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
    std::cout << "Error: of WSAStatus: " << gai_strerror(status) << std::endl;

    return status;
  }
  std::cout << "Enter domin: " << std::endl;
  std::getline(std::cin, domin);

  if (status = getaddrinfo(domin.c_str(), "80", &hints, &res) != 0) {
    std::cout << ("Error: of getaddrinfo", gai_strerror(status));
    return status;
  };
  
  char ipstr[256];
  const char* sendbuf = ( "POST  /HTTP / 1.0\r\n""Content-Type: application/x-www-form-urlencoded\r\n""Content-Length: %d\r\n");
  char bufrecv[10000];
  int s;
  
  for (p = res; p != NULL; p = p->ai_next) {
    const char* ipver;
    void* addr;
    if (p->ai_family == AF_INET) {
      struct sockaddr_in* ipv4 = (struct sockaddr_in*)p->ai_addr;
      addr = &(ipv4->sin_addr);
      ipver = "IPv4: ";
    }
    else {
      struct sockaddr_in6* ipv6 = (struct sockaddr_in6*)p->ai_addr;
      addr = &(ipv6->sin6_addr);
      ipver = "IPv6: ";
    }
    inet_ntop(p->ai_family, addr, ipstr, sizeof(ipstr));
    std::cout << "addres: " << ipver << ipstr << std::endl;
    
    if (s = socket(p->ai_family, p->ai_socktype, p->ai_protocol) == INVALID_SOCKET)
    {
      std::cout << "error of socket: " << WSAGetLastError() << std::endl;
      continue;
    }
    
    if ((connect(s, p->ai_addr, p->ai_addrlen)) == INVALID_SOCKET) {
      std::cout << "Error of connect: " << WSAGetLastError() << std::endl;
      continue;
    }

    send(s, sendbuf, sizeof(sendbuf), 0);
    
    recv(s, bufrecv, sizeof(bufrecv), 0);
    
  };
  freeaddrinfo(res);
  WSACleanup();
  system("pause");
  return 0;
}

60bbc7469281d351586338.png60bbc749f15f9906722403.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-06-05
@mercy_smile

Arrange the parentheses in the if where you create the socket. Comparison takes precedence over assignment

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question