2017-10-07 104 views
-2

我試圖設置一個默認端口號,當沒有端口輸入到C socket編程中。有誰知道我該怎麼做?我在嘗試時不斷收到分段錯誤。C socket編程沒有輸入端口

代碼:

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

我嘗試了默認設置12345當ARGC = 2,但我得到段錯誤!任何幫助,將不勝感激!

+1

顯示設置默認值的代碼,我們可以幫助您修復它。 – Barmar

+2

「*我嘗試將argc!= 2 *中的默認值設置爲12345」在哪裏? – alk

回答

5

您可以使用條件表達式。

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

簡潔明瞭。但讀者需要注意的是,如果'argv [1]'不能被信任爲適當的整數端口值,'stroul()'會更加健壯。 'atoi()'不處理''xyzzy「'好吧...... –