读取套接字缓冲区不读取

时间:2019-06-17 18:57:22

标签: c sockets

这可能是一个简单的问题,但是当我尝试读取数据时,我尝试使用套接字API修改来自Geeks for Geeks [site] 1的代码来读取服务器响应,它在valread = read(server_fd, buffer, 2048);行中被永久阻止,并且不执行任何打印。我在做错什么吗?

#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>

int send_request() {
  int server_fd, new_socket, valread;
  struct sockaddr_in address;
  int opt = 1;
  int addrlen = sizeof(address);
  char buffer[512] = {0};
  char *hello = "Hello from server";

  // Creating socket file descriptor
  if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
    perror("socket failed");
    exit(EXIT_FAILURE);
  }

  // Forcefully attaching socket to the port 8080
  if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
    perror("setsockopt");
    exit(EXIT_FAILURE);
  }

  // CONNECT TO HOST
  struct hostent *he;
  char* host = "www.columbia.edu";
  he = gethostbyname(host);

  if(!he) {
    printf("Host doesn't exist!\n");
    return 0;
  }

  address.sin_family = AF_INET;
  bcopy(he->h_addr, &address.sin_addr, sizeof(struct in_addr));
  address.sin_port = htons(80);


  if(connect(server_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_in)) < 0) {
  printf("Error in the connection");
    return 0;
  }

  valread = read(server_fd, buffer, 2048);

  printf("%s\n", buffer);
  printf("%d\n", valread);
  printf("%d\n", errno);
  return 0;
}

int main(int argc, char const *argv[]) {
  send_request();
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您正在连接到HTTP服务器。 HTTP协议指定客户端(即与服务器建立连接的一方)必须首先发送请求。您没有发送请求,因此服务器不会向您发送回复。

另外,这是一个错误:

valread = read(server_fd, buffer, 2048);

printf("%s\n", buffer);

%s格式说明符只能与C样式的字符串一起使用。不能用于任意数据。一方面,它如何知道要输出多少字节?当前包含信息的唯一位置是valread,您没有将其传递给printf