2012-02-10 82 views
2

嗨我創建了一個函數,它接受一個可接受的sockFD作爲輸入並將表示形式的IP地址輸出到一個字符串。該函數似乎工作正常,直到我打開包裝字符串與inet_ntop返回一個空指針,從而給我我的錯誤的調用。該錯誤讀取爲設備上沒有空間,我不明白,因爲我有大量的內存和ROM。無論如何波紋管是我正在使用的功能。inet_ntop:設備上沒有剩餘空間

void getTheirIp(int s, char *ipstr){ // int s is the incoming socketFD, ipstr points the the calling 
        // functions pointer. 
    socklen_t len; 
    struct sockaddr_storage addr; 
    len = sizeof(addr);   //I want to store my address in addr which is sockaddr_storage type 
    int stat; 
    stat = getpeername(s, (struct sockaddr*)&addr, &len); // This stores addrinfo in addr 
printf("getTheirIP:the value of getpeername %d\n",stat); 
    // deal with both IPv4 and IPv6: 
    if ((stat=addr.ss_family) == AF_INET) { // I get the size of the sock first 
     printf("getTheirIP:the value of addr.ss_family is %d\n",stat); 
     ipstr = malloc(INET_ADDRSTRLEN); // I allocate memory to store the string 
     struct sockaddr_in *s = (struct sockaddr_in *)&addr; // I then create the struct sockaddr_in which 
           // is large enough to hold my address 
     if(NULL == inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr))){ // I then use inet_ntop to 
     printf("getTheirIP:the value of inet_ntop is null\n");// retrieve the ip address and store 
     perror("The problem was");    // at location ipstr 
     } 

    } else { // AF_INET6 this is the same as the above except it deals with IPv6 length 
     ipstr = malloc(INET6_ADDRSTRLEN); 
     struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr; 
     inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof(ipstr)); 
    } 
    printf("%s",ipstr); 
} 

我忽略了程序的其餘部分,因爲它太大而不適合我只想着重於修復這部分。然而,下面我將向你展示我的main()的一部分,它調用這個函數。

newSock = accept(listenSock,(struct sockaddr *)&their_addr,&addr_size); 
    char *someString; 
    getTheirIp(newSock,someString); 

任何幫助將是偉大的。謝謝!

回答

7
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr)) 

sizeof是錯誤的,因爲ipstr是一個指針(它會產生指針的大小,像48東西)。您需要傳遞ipstr緩衝區的可用長度。

+0

哦,我明白了,你的意思是我分配了多少內存,而不是地址的實際大小。你是這個意思嗎?我認爲sizeof()獲得了分配的內存量。謝謝!!! – 2012-02-10 22:44:48

+1

老兄你完全統治,它的工作......謝謝再次感謝! – 2012-02-10 22:47:07

4

如在手冊頁所解釋的,從inet_ntop得到ENOSPC指:

轉換後的地址串將超過由給定大小的大小。

你給的sizeof(ipstr)作爲大小參數,它是存儲在字符指針ipstr需要的量。您需要將它傳遞給緩衝區的大小。

1

對於初學者來說,我會使用一個雙指針來代替:

void getTheirIp(int s, char **ipstr_pp) 

下一頁 - 這是錯誤的:ipstr是一個4字節的指針:

inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr) 

我想你想「 INET_ADDRSTRLEN「。

最後,我鼓勵你打印出實際的錯誤#。或者至少剪切/粘貼完整的perror()文本(我相信它應該包含錯誤#)。

+0

JFTR:perror()通常不會包含errno號碼,但包含的strerror(errno)也一樣好。確切地說,POSIX說它應該包含用戶指定的字符串,冒號,然後strerror()會給出相同的消息。 – fnl 2012-02-10 23:05:32

+0

雙指針回答我會有的問題。謝謝。 – 2012-02-10 23:55:35

相關問題