1

我正在从 Jon Erickson 的书 Hacking, the Art of Exploitation 中学习,我对他提供的简单代码示例感到困惑。代码是设置一个简单的服务器,但是当我编译它(没有错误)并运行代码时,它挂起

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "hacking.h"

#define PORT 7890   // the port users will be connecting to

int main(void) {
int sockfd, new_sockfd;  // listen on sock_fd, new connection on new_fd
struct sockaddr_in host_addr, client_addr;  // my address information
socklen_t sin_size;
int recv_length=1, yes=1;
char buffer[1024];

if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
    fatal("in socket");

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
    fatal("setting socket option SO_REUSEADDR");

host_addr.sin_family = AF_INET;      // host byte order
host_addr.sin_port = htons(PORT);    // short, network byte order
host_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
memset(&(host_addr.sin_zero), '\0', 8); // zero the rest of the struct

if (bind(sockfd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr)) == -1)
    fatal("binding to socket");

if (listen(sockfd, 5) == -1)
    fatal("listening on socket");

while(1) {    // Accept loop
    sin_size = sizeof(struct sockaddr_in);
    new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size);
    if(new_sockfd == -1)
        fatal("accepting connection");
    printf("server: got connection from %s port %d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
    send(new_sockfd, "Hello World!\n", 13, 0);
    recv_length = recv(new_sockfd, &buffer, 1024, 0);
    while(recv_length > 0) {
        printf("RECV: %d bytes\n", recv_length);
        dump(buffer, recv_length);
        recv_length = recv(new_sockfd, &buffer, 1024, 0);
    }
    close(new_sockfd);
}
return 0;
}

我做了一点 printf() 来找出我挂在哪里,结果就在这条线上

sin_size = sizeof(struct sockaddr_in);

我不确定这是否与我的环境有关,或者我缺少某些东西。本书使用的环境无法再更新(Ubuntu的一些旧版本)。所以我目前正在使用最新的。

有人可以向我解释为什么该程序不起作用吗?

如果在学习网络章节之前需要了解一些基础知识,请告诉。

4

3 回答 3

2

在收到来自客户端程序的传入连接accept后,该程序才会继续运行。sizeof您的 printf 显示 accept 被调用但被阻止。

您需要使用正确的选项(IP / 端口)编译和运行客户端以连接到此服务器程序。

更新 如果 192.168.42.248 来自书中,那么您可能正在尝试连接到错误的 IP。试试telnet 127.0.0.1 7890

于 2013-02-14T05:27:17.707 回答
2

它是一个服务器,它会“挂起”,直到你连接到端口 7890。这就是程序的重点(更多细节,它会阻塞,因为accept()正在等待连接)

假设您正在运行 unix,请在运行时尝试echo "hi there" | nc localhost 7890在同一台机器上输入终端,您将看到它是如何“解除阻塞”的

于 2013-02-14T05:30:10.963 回答
0

根据您线程中飞来飞去的所有评论,我建议使用以下命令行连接 telnet:telnet localhost 7890

telnet 将要连接的主机和要连接到该主机的端口作为参数。使用“localhost”类似于使用环回 IP 127.0.0.1。

为什么连接服务器可以解决“挂起”?accept 是阻塞的,您可以在手册页或编程环境的任何其他文档中阅读。这意味着该函数在客户端连接之前不会返回。连接后,该函数返回为连接客户端创建的可用于通信的套接字的句柄。

于 2013-02-14T05:41:23.860 回答