2012-10-15 44 views
0

可能重复:
Checking value of argc校验值

我要去套接字编程卡,这是我的Socket编程简单的C代码开发了Linux的Ubuntu的,但代码不起作用,并在第一次退出,如果condtion代表端口的argc值。 我需要帮助,请:)

#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; 

}

+0

你能显示你正在使用的命令吗? – MByD

+0

我在eclipse上运行代码,输出是用法:/ home/dell/Desktop/C/np/Debug/np MostafaKhattab

+0

你是怎么让它在Eclipse中运行的? –

回答

0

我不完全相信你问什么,但我相信你都搞不清是怎么if语句来检查传递给你的程序的参数个数作品。在命令行,如果用户运行:

myprogram 

argv值将{"myprogram"}argc将是1.在另一方面,如果你运行:

myprogram 23 

的价值argv将为{"myprogram", "23"}argc将为2.我认为在运行该程序时,您只是没有为端口号传递适当的参数。

+0

是的,现在的问题我该如何使argc为2或更高,我不明白如何克服这个 – MostafaKhattab

+0

当你在命令中运行时,'argc'由你传递给程序的参数数量控制线。如果你运行'myprogram 23 hello arg',那么'argc'将等于4。 – nickolayratchev