服務器程序:運行時綁定錯誤
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<unistd.h>
#define MYPORT 4444
#define BACKLOG 100
#define MAXBUFSIZE 100
int main(void)
{
int sockfd,newfd,sin_size,i,count;
struct sockaddr_in my_addr,their_addr;
char request[MAXBUFSIZE] = "This is the servers request";
char buf[100];
/*Create Socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
printf("\nSocket created");
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr =inet_addr("10.228.37.9");
/*Bind Socket*/
i=bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
if(i<0)
{
printf("\nBind Error");
exit(1);
}
else
{
printf("\nBind socket");
}
/*Listen */
listen(sockfd, BACKLOG) ;
if(listen(sockfd, BACKLOG)==-1)
{
printf("\nError in listening");
}
else
printf("Listened Successfully");
sin_size = sizeof(struct sockaddr_in);
/*Accept*/
newfd = accept(sockfd, (struct sockaddr *)&their_addr,&sin_size);
/*Receive from Client*/
count = recv(newfd, buf, sizeof(buf), 0);
if (count < 0)
{
printf("recv error");
exit(1);
}
buf[count]='\0';
printf("\nReceived: %s",buf);
printf("\nSuccessful");
/*Send to Client*/
if (send(newfd, request, (int)strlen(request), 0) < 0)
{
printf("send error");
exit(1);
}
return 0;
}
這是使用套接字在C服務器程序, 沒有編譯錯誤,但在運行時程序應等待客戶端但它顯示綁定錯誤。在socket服務器程序 運行時綁定錯誤
提示修復「地址已在使用」 設置標誌
SO_REUSEADDR
:'strerror(errno)'。 – trojanfoe你爲什麼試圖綁定到特定的IP地址?通常我們綁定到INADDR_ANY以接受所有連接... – Medinoc
@Medinoc雖然綁定到特定的IP地址沒有任何問題。我的錢在'EADDRINUSE'上。 – trojanfoe