1
我正在爲一個服務器編寫一個簡單的套接字程序,其中我在listen()
調用中掛起了一個掛起。令人驚訝的是,這段代碼掛起:Linux Socket編程:listen()調用顯示意外行爲
if((res = listen(sockfd, 5)) == -1)
{
perror("Error in listening over socket");
exit(1);
}
這怎麼可能?以下是我的完整代碼以供參考:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define MYPORT 7891
int main()
{
int sockfd, newfd, res;
struct sockaddr_in my_addr, their_addr;
socklen_t their_addr_size;
char msg[100] = {'\0'};
/* open a socket for the server */
if((sockfd = socket(AF_INET, SOCK_STREAM,0)) == -1)
{
perror("Error opening socket");
exit(1);
}
printf("Socket opened successfully\n");
/* specify the interface details, where the server should listen for incoming messages. It is set by bind */
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr = INADDR_ANY; /* listen on every interface, eth0, wlan, whatever f**kin place */
memset(&(my_addr.sin_zero),0,8);
if((res = bind(sockfd, (struct sockaddr *)&(my_addr), sizeof(struct sockaddr_in))) == -1)
{
perror("Error while bind()");
exit(1);
}
printf("Bind() is successfull\n");
/* listen on the socket, setting the waiting queue size to max 5 connections. Other connections will get ECONNREFUSED error */
if((res = listen(sockfd, 5)) == -1)
{
perror("Error in listening over socket");
exit(1);
}
// if(listen(sockfd,5)==0)
// printf("Listening\n");
// else
// printf("Error\n");
printf("Listening....");
/* accept incoming request */
their_addr_size = sizeof(struct sockaddr_in);
if((newfd = accept(sockfd, (struct sockaddr *)&their_addr, &their_addr_size)) == -1)
{
perror("Error accepting connection");
exit(1);
}
/* write data */
printf("Enter the data to be sent\n");
while(1)
{
scanf("%s",msg);
write(newfd, msg, strlen(msg));
}
/* though it never comes here due to infinite while loop */
close(newfd);
close(sockfd);
return 0;
}
我沒有收到「正在收聽...」。