使用套接字的 c 中的服务器程序:
#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 中的服务器程序,没有编译错误,但在运行时程序应该等待客户端,但它显示绑定错误。套接字服务器程序中的运行时绑定错误