简体   繁体   English

C命令行密码

[英]C command line password

So I'm trying to create a C program where you must input the password on the command line, like ./login password1 And if the password is password1, it'll say something. 所以我正在尝试创建一个C程序,你必须在命令行输入密码,比如./login password1如果密码是password1,它会说些什么。 If not, it prints another message. 如果没有,它会打印另一条消息。 This is the code I have now: 这是我现在的代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  if (argc < 2) {
    printf("usage: %s <password>\n", argv[0]);
  }
  char pass = "password";
  if (argc == pass) {
    printf("Right\n");
  } else {
    printf("Wrong\n");
  }
}

But it wont work. 但它不会工作。

char pass = "password";

You're trying to assign a string to a char . 您正在尝试将字符串分配给char That won't work! 那不行! Instead, you need need to declare pass as a char[] like this: 相反,您需要将pass声明为char[]如下所示:

char pass[] = "password";

Next problem: 下一个问题:

if(argc == pass)

argc is the number of command line arguments passed to your program (including the program name as the first). argc是传递给程序的命令行参数的数量(包括作为第一个的程序名称)。 What you want is argv , which contains the actual arguments. 你想要的是argv ,它包含实际的参数。 Specifically, you probably want argv[1] . 具体来说,你可能想要argv[1]

You can't just go argv[1] == pass as that compares the location of the two strings. 你不能只是去argv[1] == pass因为它比较了两个字符串的位置。 To compare strings, you need to use strcmp() . 要比较字符串,您需要使用strcmp() This function compares two strings and returns 0 if they're equal (there's good reason for that, but leave it for now). 此函数比较两个字符串,如果它们相等则返回0(这是有充分理由的,但现在就保留它)。 The former is like comparing two houses by checking if they have exactly the same street address; 前者就像比较两个房子,检查他们是否有完全相同的街道地址; the latter is like comparing the houses with each other brick-by-brick. 后者就像把房子相互比较一样。 (sniped from @caf) (从@caf嗤之以鼻)

So the line becomes: 这条线变成:

if (strcmp(argv[1], pass) == 0)

Put those fixes together and it should work. 把这些修复放在一起,它应该工作。 Please also work on improving the indentation of your code. 还请努力改进代码的缩进。 It'll make it much easier to read, not only for others but yourself in a few weeks time. 它会让你更容易阅读,不仅仅是为了别人,而是在几周之内。

You're comparing argc - the count of command line arguments - with the "password" string pointer. 您将argc (命令行参数的数量)与"password"字符串指针进行比较。

For a start, you need to use argv[1] instead of argc . 首先,您需要使用argv[1]而不是argc You also need to use a suitable strcmp function rather than just comparing the pointers. 您还需要使用合适的strcmp函数,而不仅仅是比较指针。

Finally, inputting passwords via the command line is usually a bad idea due to security considerations. 最后,出于安全考虑,通过命令行输入密码通常是个坏主意。 On many systems the command line may be visible to other users (eg via the "ps" command). 在许多系统上,命令行可能对其他用户可见(例如,通过“ps”命令)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM