2015-11-16 71 views
0

我一直在試圖修改http://beej.us/guide/bgnet/「selectserver.c」,並允許用戶定義的端口號並使用它,而不是用戶自定義端口號

#define PORT "9034" // port we're listening on 

我試圖使這項工作...

int PORT; 
if (argc == 1) { 
    printf("\nNo argument passed. See example: ./selectserver 1234 \n\n"); 
    exit(-1); 
} else { 
    PORT = atoi(argv[1]); 
    printf("PORT NO. : %d \n", PORT); 
} 

char* ptrPORT = (char *)&PORT; 

...

這裏的代碼我修改:

/* 
** selectserver.c -- a cheezy multiperson chat server 
*/ 

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 
#include <netdb.h> 

//#define PORT "10000" // port we're listening on 

// get sockaddr, IPv4 or IPv6: 
void *get_in_addr(struct sockaddr *sa) 
{ 
    if (sa->sa_family == AF_INET) { 
     return &(((struct sockaddr_in*)sa)->sin_addr); 
    } 

    return &(((struct sockaddr_in6*)sa)->sin6_addr); 
} 

int main(int argc, char *argv[]) { 
    int PORT; 
    fd_set master; // master file descriptor list 
    fd_set read_fds; // temp file descriptor list for select() 
    int fdmax; // maximum file descriptor number 
    int listener;  // listening socket descriptor 
    int newfd;  // newly accept()ed socket descriptor 
    struct sockaddr_storage remoteaddr; // client address 
    socklen_t addrlen; 
    char buf[256]; // buffer for client data 
    int nbytes; 

    char remoteIP[INET6_ADDRSTRLEN]; 

    int yes=1;  // for setsockopt() SO_REUSEADDR, below 
    int i, j, rv; 

    struct addrinfo hints, *ai, *p; 

    FD_ZERO(&master); // clear the master and temp sets 
    FD_ZERO(&read_fds); 

    // get us a socket and bind it 
    memset(&hints, 0, sizeof hints); 
    hints.ai_family = AF_UNSPEC; 
    hints.ai_socktype = SOCK_STREAM; 
    hints.ai_flags = AI_PASSIVE; 

    if (argc == 1) { 
     printf("\nNo argument passed. See example: ./selectserver 1234 \n\n"); 
     exit(-1); 
    } else { 
     PORT = atoi(argv[1]); 
     printf("PORT NO. : %d \n", PORT); 
    } 

    char* ptrPORT = (char *)&PORT; 

    if ((rv = getaddrinfo(NULL, ptrPORT, &hints, &ai)) != 0) { 
      fprintf(stderr, "selectserver: %s\n", gai_strerror(rv)); 
      exit(1); 
    } 

    for(p = ai; p != NULL; p = p->ai_next) { 
     listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol); 
     if (listener < 0) { 
      continue; 
     } 

     // lose the pesky "address already in use" error message 
     setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); 

     if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) { 
       close(listener); 
      continue; 
     } 

     break; 
    } 

    // if we got here, it means we didn't get bound 
    if (p == NULL) { 
     fprintf(stderr, "selectserver: failed to bind\n"); 
     exit(2); 
    } 

    freeaddrinfo(ai); // all done with this 

    // listen 
    if (listen(listener, 10) == -1) { 
     perror("listen"); 
     exit(3); 
    } 

    // add the listener to the master set 
    FD_SET(listener, &master); 

    // keep track of the biggest file descriptor 
    fdmax = listener; // so far, it's this one 

    // main loop 
    for(;;) { 
     read_fds = master; // copy it 
     if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) { 
      perror("select"); 
      exit(4); 
     } 

     // run through the existing connections looking for data to read 
     for(i = 0; i <= fdmax; i++) { 
      if (FD_ISSET(i, &read_fds)) { // we got one!! 
       if (i == listener) { 
       // handle new connections 
       addrlen = sizeof remoteaddr; 
       newfd = accept(listener, 
        (struct sockaddr *)&remoteaddr, 
        &addrlen); 
       if (newfd == -1) { 
        perror("accept"); 
       } else { 
        FD_SET(newfd, &master); // add to master set 
        if (newfd > fdmax) { // keep track of the max 
         fdmax = newfd; 
        } 
        printf("selectserver: new connection from %s on " 
         "socket %d\n", 
         inet_ntop(remoteaddr.ss_family, 
          get_in_addr((struct sockaddr*)&remoteaddr), 
          remoteIP, INET6_ADDRSTRLEN), newfd); 
     } 
      } else { 
       // handle data from a client 
       if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) { 
        // got error or connection closed by client 
        if (nbytes == 0) { 
         // connection closed 
         printf("selectserver: socket %d hung up\n", i); 
        } else { 
         perror("recv"); 
        } 
        close(i); // bye! 
        FD_CLR(i, &master); // remove from master set 
       } else { 
        // we got some data from a client 
        for(j = 0; j <= fdmax; j++) { 
         // send to everyone! 
         if (FD_ISSET(j, &master)) { 
          // except the listener and ourselves 
          if (j != listener && j != i) { 
           if (send(j, buf, nbytes, 0) == -1) { 
            perror("send"); 
       } 
       } 
      } 
      } 
     } 

       } // END handle data from client 
      } // END got new incoming connection 
     } // END looping through file descriptors 
    } // END for(;;)--and you thought it would never end! 

    return 0; 
} 

它會順利編譯。 現在我的問題是在執行時會顯示出這一點,我真的不知道如何解決它(我們只是在昨天有一個班級討論所以我基本上小白約socket編程)

./selectserver 10000 

PORT NO. : 10000 
selectserver: nodename nor servname provided, or not known 

請多多包涵謝謝!

+0

你真的認爲'的printf(「PORT NO: %d \ n「,」9034「);'會產生有用的結果嗎?您不能將字符串(const char *)變量傳遞給需要整數的函數。怎麼樣'int num =「1」+「2」'?當然,這不會工作。 'int num = 1 + 2;'另一方面是完全不同的問題。 ;) – enhzflep

+0

'getaddrinfo'不以這種方式工作。閱讀手冊頁。 –

+0

這就是爲什麼它使用類型強制轉換'char * ptrPORT =(char *)&PORT;'這樣它就不會違反'getaddrinfo'的參數嗯......我不知道出了什麼問題:( – pixiedust27

回答

1

getaddrinfo將指針指向以空字符結尾的字符串作爲第二個參數。

char* ptrPORT = (char *)&PORT; 

上面的語句是類型鑄造的指針int成一個指向炭。這並沒有改變它仍然指向int的事實。現在,如果你仔細想想,你可以看到getaddrinfo不會知道如何正確讀取你的值 - 它不是一個真正的以空字符結尾的字符串。

然而,argv[1]是一個空值終止字符串,所以我的建議是將其原樣,而不是試圖將其轉換:

char* ptrPORT = argv[1]; 
+0

謝謝,男人!現在是功能:D – pixiedust27

+0

歡迎您歡呼!歡呼! – Kalu

0

服務參數接受char *和int。 但是,你真的想要依靠char *和int之間的識別嗎? 在手冊頁enter link description here上,服務參數可以是一個字符串形式的數字。當hints.ai_flags設置爲AI_NUMERICSERV時。