C 绑定无效参数
我正在玩unix套接字。代码编译得很好,但我在执行时收到以下消息C 绑定无效参数,c,sockets,network-programming,C,Sockets,Network Programming,我正在玩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 so
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;
}
#包括
#包括
#包括
#包括
#包括
#定义端口7000
int main(){
内部插座描述;
地址中的结构sockaddr_;
socket\u desc=socket(AF\u INET,SOCK\u STREAM,0);
如果(套接字描述==-1)
perror(“创建套接字”);
/*在套接字()中创建的套接字类型*/
address.sin_family=AF_INET;
address.sin_addr.s_addr=INADDR\u ANY;
/*设置端口*/
address.sin_port=htons(port);
而(1){
/*将套接字绑定到上面指定的端口*/
if(绑定(socket_desc,(struct sockaddr*)和地址,sizeof(地址))<0{
佩罗(“错误”);
出口(-1);
}
}
返回0;
}
问题是您尝试绑定了不止一次--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);
}
}
是否尝试将参数传递给
main()
?@MZON Zeros与INADDR\u ANY相同。你的方式更好。
#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);