这是我的代码:
int main(int argc, char * argv[])
{
if (1 == argc) { // if nothing go in
printf("Usage: %s <port>\n", argv[0]);
exit(-0);
}
int port = strtol(argv[1], NULL, 10); //pass
if (0 == port) {
perror("Invalid port");
exit(-1);
}
struct sigaction sa;
sa.sa_handler = &handle_sigchld;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
if (sigaction(SIGCHLD, &sa, 0) == -1) {
perror("Unable to register sigaction");
exit(-2);
}
int s = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == s) {
perror("Unable to create server socket");
exit(-3);
}
int optval = 1;
if (0 != setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) {
perror("Unable to setsockopt");
exit(-4);
}
struct sockaddr_in bind_addr = {
.sin_family = AF_INET,
.sin_port = htons(port)
};
if (0 != bind(s, (struct sockaddr *) &bind_addr, sizeof(bind_addr))) {
perror("Unable to bind socket");
exit(-5);
}
if (0 != listen(s, 10)) {
perror("Unable to listen");
exit(-6);
}
while (1) {
int s_ = accept(s, NULL, NULL);
sleep(BRUTE_FORCE_TIMEOUT); //here is the stop !!!(but after I delete this, it still stops but in the first line of this while loop)
if (-1 == s_) {
perror("Unable to accept");
continue;
}
pid_t child_pid = fork();
if (-1 == child_pid) {
perror("Unable to fork");
goto accept_cleanup;
}
if (0 == child_pid) {
close(s);
handle(s_);
exit(0);
}
accept_cleanup:
close(s_);
}
exit(0);
}
void handle(int s)
{
char inbuf[4096];
dup2(s, 0);
dup2(s, 1);
setbuf(stdout, NULL);
alarm(ALARM_TIMEOUT_SEC);
printf("crackme> ");
if (NULL == fgets(inbuf, sizeof(inbuf), stdin))
{
return;
}
right_trim(inbuf);
if(is_correct(inbuf))
{
printf("Good job!\n");
}
}
要运行此程序,我需要运行程序名称和端口号。 例如:
./my_file 6000
问题是当我运行端口已经运行时,我收到一个错误,表明该端口已在使用中。 如果我尝试使用端口0运行它,我会收到端口无效的错误:成功。 如果我只使用一个随机端口运行它,Linux下行线并没有任何反应。
当我在gdb中调试它时,它会在sleep
行停止,所以我删除了这一行,然后它再次停止,但现在在while循环的第一行(while (1) { int s_ = ...
)。
为什么会这样?