为什么bind函数返回-1(绑定失败)?

时间:2014-11-20 23:38:49

标签: c client server

我正在尝试将套接字绑定到IP地址以及它将侦听连接的端口。这是我的相关代码(w注释和调试打印语句)

#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时,我看到bind函数将返回-1表示错误(绑定失败)。基于我的代码,有谁知道为什么这个操作失败了?我查看了我的代码,我想我已经完成了所有设置(所有评论)。我甚至确保我使用的端口号在分配给应用程序的范围内(1024 - 49151)。基于http://man7.org/linux/man-pages/man2/socket.2.html,我知道套接字已成功创建(返回值为3,而不是-1)

1 个答案:

答案 0 :(得分:0)

./err 
value of socket:3
value of bind: 0

所以,它有效。代码没有错。很可能端口应该已经被另一个程序使用,或者程序的早期版本处于清理状态,使端口忙碌。要确认,请在调用bind后立即使用perror()。还要查找SO_REUSEADDR套接字选项,以允许绑定处于清理状态的端口。