我在套接字编程中遇到错误。执行时它将在 bind() 函数之后挂起。这是代码:
int socket_rcv,new_socket;
struct sockaddr_in add1, add2;
int test[100];
buffer= test;
printf("\n Initializing Socket....");
socket_rcv = socket(AF_INET,SOCK_STREAM,0);
if(socket_rcv == -1)
{
perror("Socket not created.Error:");
return 1;
}
printf("\n Socket created");
add1.sin_family = AF_INET;
add1.sin_addr.s_addr = htonl(INADDR_ANY);
add1.sin_port = htons(port_num);
if((socket_rcv = bind(socket_rcv,(struct sockaddr*)&add1,sizeof(add1))) == -1)
{
perror("binding failed. Error:");
return 1;
}
printf("\n Bind completed");
if(listen(socket_rcv,10) == -1)
{
perror("listen failed.Error:");
return 1;
}
socklen_t sizes = sizeof(add2);
printf("\n Waiting for connection.....");
new_socket = accept(socket_rcv, (struct sockaddr*) &add2, &sizes);
if(new_socket != -1)
{
printf("\n %d, Accepted",new_socket);
if(recv(new_socket,(char*)buffer,100,1)<0)
{
printf("\n No data received from %d socket",new_socket);
return 1;
}
printf("\n Data Received\n");
}
else
{
perror("Accept failed. Error:");
return 1;
}
close(new_socket);
close(socket_rcv);
return 0;
我的问题是在执行这段代码时,它会在 bind() 函数之后挂起。最后显示的那一行是“Bind Completed”,之后就会挂起。那么 bind() 函数有问题吗?