我想將一個套接字綁定到IP地址和它將監聽連接的端口。這裏是我的相關代碼(W註釋和調試打印語句)爲什麼bind函數返回-1(綁定失敗)?
#define PORTNUM 2345
int main(int argc, char *argv[])
{
// socket info about client connecting to server
struct sockaddr_in dest;
//socket info about server
struct sockaddr_in serv;
//socket used to listen for incoming connections
int mysocket;
//zero the struct before filling the fields
memset(&serv, 0, sizeof(serv));
//set connection type to tcp/ip
serv.sin_family = AF_INET;
//set should be be bound to ip of the machine on which process currently executing
serv.sin_addr.s_addr = htonl(INADDR_ANY);
//set server port number
serv.sin_port = htons(PORTNUM);
//create the socket to liste for connection
mysocket = socket(AF_INET, SOCK_STREAM, 0);
printf("value of socket:%d\n", mysocket);
// bind serv information to mysocket
int v= bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));
printf("value of bind: %d\n", v);
return 1;
}
這裏是我的調試打印語句當我運行我的代碼
Value of socket: 3
Value of bind: -1
當我閱讀文檔http://linux.die.net/man/2/bind,只見那綁定函數將返回-1錯誤(綁定失敗)。根據我的代碼,有沒有人知道爲什麼這個操作失敗?我查看了我的代碼,我想我已經設置了一切(所有評論)。我甚至確保我使用的端口號在分配給應用程序的範圍內(1024 - 49151)。基於http://man7.org/linux/man-pages/man2/socket.2.html,我知道套接字創建成功(3返回值,而不是-1)
調用'perror(「bind」);'打印實際的錯誤。請參閱您鏈接所有錯誤綁定可以返回的文檔?這些保存在一個名爲'errno'的全局變量中,您可以通過包含'errno.h'直接訪問它。 'perror()'是'stdio.h'中聲明的一個輔助函數。 – indiv 2014-11-20 23:45:18
我在哪裏打電話perror?調用綁定之後? – committedandroider 2014-11-20 23:47:19
是的,在你做任何事之前。你希望你的代碼像'int v = bind(...);如果(v <0){perror(「bind」); }' – indiv 2014-11-20 23:48:15