重要编辑:在不改变任何内容后,它随机开始工作。我不知道为什么,但感谢所有的帮助!
我正在尝试学习如何使用C创建可以互相交互的客户端和服务器。我已经做了一些研究并遵循了教程,我觉得我对它是如何工作的,但是当我尝试运行该示例时,客户端无法连接到服务器。
以下是客户端代码:
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc <3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
printf("PORT NUMBER: %d\n", portno);
/* Create a socket point */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
exit(1);
}
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
/* Now connect to the server */
if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
perror("ERROR connecting");
exit(1);
}
return 0;
}
这是服务器代码:
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
int main( int argc, char *argv[] )
{
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
/* First call to socket() function */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(1);
}
printf("Successfully opened socket\n");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 5771;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
/* Now bind the host address using bind() call.*/
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR on binding");
exit(1);
}
printf("Successfully bound socket\n");
/* Now start listening for the clients, here process will
* go in sleep mode and will wait for the incoming connection
*/
printf("Commence listening\n");
listen(sockfd,50);
clilen = sizeof(cli_addr);
/* Accept actual connection from the client */
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
if (newsockfd < 0) {
perror("ERROR on accept");
exit(1);
}
printf("CONNECTED.\n");
return 0;
}
服务器的输出如下:
Successfully opened socket
Successfully bound socket
Commence Listening
我在这里读到了一些与连接拒绝错误有关的问题,他们说错误的最可能原因是端口没有打开。但是,如果我的服务器一直到听取步骤,那不应该意味着端口实际上是打开的吗?我不认为这与将错误的IP地址传递给客户端有关,因为我尝试传入错误的IP地址,并且在连接被拒绝之前错误。
有没有人知道为什么我会收到此错误?