[英]Read socket buffer not reading
this maybe is a simple question but I'm trying to just read a server response using the sockets API adapting the code from Geeks for Geeks [site] 1 , when I try to read the data, it becomes blocked forever in the valread = read(server_fd, buffer, 2048);
这可能是一个简单的问题,但是我试图使用套接字API来读取服务器响应,以适应来自Geeks for Geeks [site] 1的代码,当我尝试读取数据时,它在
valread = read(server_fd, buffer, 2048);
永远被阻塞valread = read(server_fd, buffer, 2048);
line, and doesn't execute any of the prints. 行,并且不执行任何打印。 Am I doing something wrong?
难道我做错了什么?
#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;
}
You are connecting to an HTTP server. 您正在连接到HTTP服务器。 The HTTP protocol specifies that the client (that is, the side that makes the connection to the server) must send a request first.
HTTP协议指定客户端(即与服务器建立连接的一方)必须首先发送请求。 You aren't sending a request, so the server is not going to send you a reply.
您没有发送请求,因此服务器不会向您发送回复。
Also, this is a bug: 另外,这是一个错误:
valread = read(server_fd, buffer, 2048);
printf("%s\n", buffer);
The %s
format specifier can only be used with C-style strings. %s
格式说明符只能与C样式的字符串一起使用。 It can't be used for arbitrary data. 不能用于任意数据。 For one thing, how would it know how many bytes to output?
一方面,它如何知道要输出多少字节? The only place that information is currently contained is in
valread
, and you didn't pass it to printf
. 当前包含信息的唯一位置是
valread
,您没有将其传递给printf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.