我有用 C 编写的服务器和客户端套接字程序。我想使用local host ipaddress 127.0.0.1
. 当我执行服务器程序时。它的输出是绑定失败并停止。如何使客户端连接到同一台笔记本电脑上的服务器(即通过本地主机)成为可能。请帮忙。
这是服务器代码(这是一个回显服务器程序):
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
main(int argc, char *argv[])
{
int clilen, sockfd, newsockfd, n, cpid;
char msg[100];
struct sockaddr_in serv_addr, cli;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket failed to establish\n");
exit(0);
}
printf("socket created\n");
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
serv_addr.sin_port = htons(atoi(argv[2]));
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("binding failed\n");
exit(0);
}
printf("binding established\n");
if (listen(sockfd, 5) < 0)
{
printf("not listening\n");
exit(0);
}
printf("listening|n");
for (;;)
{
clilen = sizeof(cli);
if ((newsockfd = accept(sockfd, (struct sockaddr *)&cli, &clilen)) < 0)
{
printf("accept failed\n");
exit(0);
}
printf("accepted\n");
cpid = fork();
if (cpid == 0)
{
n = read(newsockfd, msg, 80);
msg[n] = '\0';
write(newsockfd, msg, strlen(msg));
close(newsockfd);
exit(0);
}
}
}