gpt4 book ai didi

c - 绑定(bind)无效参数

转载 作者:太空狗 更新时间:2023-10-29 15:35:53 25 4
gpt4 key购买 nike

我正在玩 unix 套接字。代码编译正常,但我在执行时收到以下消息

Invalid argument

这是我使用的代码。我想这很简单

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>

#define PORT 7000


int main(){
int socket_desc;
struct sockaddr_in address;

socket_desc = socket(AF_INET, SOCK_STREAM, 0);

if(socket_desc == -1)
perror("Create socket");

/* type of socket created in socket() */
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
/* set port */
address.sin_port = htons(PORT);

while(1) {
/* bind the socket to the port specified above */
if(bind(socket_desc,(struct sockaddr *)&address, sizeof(address)) < 0) {
perror("Error");
exit(-1);
}
}

return 0;
}

最佳答案

问题是您尝试绑定(bind)不止一次——while(1) 循环是怎么回事?

while(1) {
/* bind the socket to the port specified above */
if(bind(socket_desc,(struct sockaddr *)&address, sizeof(address)) < 0) {
perror("Error");
exit(-1);
}
}

bind() 第一次成功,在随后的调用中失败并返回 EINVAL,这意味着(来自 man 2 bind) :

[EINVAL] socket is already bound to an address and the protocol does not support binding to a new address. Alternatively, socket may have been shut down.

作为旁注,在传入 sockaddr 之前将其清零可能是个好主意:

#include <string.h>
/* ... */

memset(&address, 0, sizeof(address));

address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);

关于c - 绑定(bind)无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20431957/

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