【问题标题】:C socket programming no port enteredC套接字编程没有输入端口
【发布时间】:2018-03-19 00:32:44
【问题描述】:

我正在尝试为在 C 套接字编程中未输入端口时设置默认端口号。有谁知道我该怎么做?我不断尝试分段错误。

代码:

#define PORT 12345

int main(int argc, char *argv[]) {

    /* Thread and thread attributes */
    pthread_t client_thread;
    pthread_attr_t attr;


    int sockfd, new_fd;  /* listen on sock_fd, new connection on new_fd */
    struct sockaddr_in my_addr;    /* my address information */
    struct sockaddr_in their_addr; /* connector's address information */
    socklen_t sin_size;
    int i=0;

    /* Get port number for server to listen on */
    if (argc != 2) {
        fprintf(stderr,"usage: client port_number\n");
        exit(1);
    }

    /* generate the socket */
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    /* generate the end point */
    my_addr.sin_family = AF_INET;         
    my_addr.sin_port = htons(atoi(argv[1]));     
    my_addr.sin_addr.s_addr = INADDR_ANY; 

我尝试在 argc != 2 时将默认值设置为 12345,但出现分段错误。任何帮助将不胜感激!

【问题讨论】:

  • 显示设置默认值的代码,我们可以帮你修复。
  • "我尝试在 argc != 2 时将默认值设置为 12345" 在哪里?

标签: c sockets numbers connection port


【解决方案1】:

您可以使用条件表达式。

#define DEFAULT_PORT 12345
my_addr.sin_port = htons(argc < 2 ? DEFAULT_PORT : atoi(argv[1]));

【讨论】:

  • 简洁明了。但是读者需要注意,如果不能相信argv[1] 是一个正确的整数端口值,那么像stroul() 这样的东西会更加健壮。 atoi() 不处理 "xyzzy" 好吧...
猜你喜欢
  • 2011-07-23
  • 2015-10-25
  • 1970-01-01
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-23
相关资源
最近更新 更多