检查 C 中 argc 的值

标签 c ubuntu argc

Possible Duplicate:
Checking value of argc

我将继续进行套接字编程,这是我在 linux-ubuntu 上开发的套接字编程简单 C 代码,但由于代表端口的 argc 值,代码无法工作并在第一个 if 条件下退出。 我需要帮助:)

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
const char APRESSMESSAGE[] = "APRESS - For Professionals, By Professionals!\n";

int main(int argc, char *argv[]) {
int simpleSocket = 0;
int simplePort = 0;
int returnStatus = 0;
struct sockaddr_in simpleServer;

if (2 != argc) {
    fprintf(stderr, "Usage: %s <port>\n", argv[0]);
    exit(1);
}
simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
printf("%i\n", simpleSocket);
if (simpleSocket <= -1) {
    fprintf(stderr, "Could not create a socket!\n");
    exit(1);
} else {
    fprintf(stderr, "Socket created!\n");
}
/* retrieve the port number for listening */
simplePort = atoi(argv[1]);
/* set up the address structure */
/* use INADDR_ANY to bind to all local addresses
 */
puts("test1");
bzero(&simpleServer, sizeof(simpleServer));
simpleServer.sin_family = AF_INET;
simpleServer.sin_addr.s_addr = htonl(INADDR_ANY);
simpleServer.sin_port = htons(simplePort);
/*
 bind to the address and port with our socket
 */
returnStatus = bind(simpleSocket, (struct sockaddr *) &simpleServer,
        sizeof(simpleServer));
if (returnStatus == 0) {
    fprintf(stderr, "Bind completed!\n");
} else {
    fprintf(stderr, "Could not bind to address!\n");
    close(simpleSocket);
    exit(1);
}
/* let's listen on the socket for connections */
returnStatus = listen(simpleSocket, 5);
if (returnStatus == -1) {
    fprintf(stderr, "Cannot listen on socket!\n");
    close(simpleSocket);
    exit(1);
}
while (1) {
    struct sockaddr_in clientName = { 0 };
    int simpleChildSocket = 0;
    int clientNameLength = sizeof(clientName);
    /* wait here */
    simpleChildSocket = accept(simpleSocket,
            (struct sockaddr *) &clientName, &clientNameLength);
    if (simpleChildSocket == -1) {
        fprintf(stderr, "Cannot accept connections!\n");
        close(simpleSocket);
        exit(1);
    }
    /* handle the new connection request
     */
    /* write out our message to the client */
    write(simpleChildSocket, APRESSMESSAGE, strlen(APRESSMESSAGE));
    close(simpleChildSocket);
}
close(simpleSocket);
return 0;

}

最佳答案

我不太确定您在问什么,但我相信您对检查传递给程序的参数数量的 if 语句如何工作感到困惑。从命令行,如果用户运行:

myprogram

argv 的值将为 {"myprogram"}argc 将为 1。另一方面,如果您运行:

myprogram 23

argv 的值将是 {"myprogram", "23"}argc 将是 2。我认为你只是运行程序时未传递适当的端口号参数。

关于检查 C 中 argc 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12904559/

相关文章:

c - 在 C 中打印字符串数组时出错

c - 是否可以在 c 中传递两个参数?

ubuntu - KVM - 无法连接到管理程序错误

asp.net-core - 如何使用 ubuntu 在本地网络上共享 asp.net 核心应用程序?

c++ - 打开一个通过命令参数做某事的函数

c - 输入的动态内存分配?

c++ - 为什么 Xcode 无法识别 argc?

C - 获取数字而不是字符串

ubuntu - 在 Electron 信息亭模式下显示屏幕键盘

c - 错误的文件描述符与 Linux 套接字 write() 错误的文件描述符 C