gpt4 book ai didi

Linux套接字编程: listen() call showing unexpected behaviour

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:00 25 4
gpt4 key购买 nike

我当时正在为服务器编写一个简单的套接字程序,我在 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;
}

我没有收到“正在收听...”。

最佳答案

这是由于缓冲了sdtout数据。执行 fflush(stdout),给出正确的打印。并且该进程现在被阻止在预期位置 accept()

关于Linux套接字编程: listen() call showing unexpected behaviour,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37725174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com