客户端向服务器发送请求时出现“无主机路由”错误(C网络)

时间:2014-08-07 18:04:54

标签: c sockets networking client-server network-protocols

我在C中有一个基本的客户端/服务器设置,只有当客户端和服务器在同一台机器上时才有效。如果我的客户端在不同的计算机上无法向我的服务器发送请求,是否有任何理由?

在这种情况下,我在虚拟机上运行服务器并尝试在主机上运行客户端。

观察:

  • 如果我在VM上启动服务器,并在VM上运行客户端并更改其地址 在客户端代码中,以便有一行

    addr.sin_addr.s_addr = inet_addr(“ 127.0.0.1 ”);

    然后我的服务器能够与我的客户端连接。这里没有错误,一切都按原样发生。

  • 如果我在我的虚拟机上启动服务器,然后在我的主机上使用我的虚拟机IP运行我的客户端:

    addr.sin_addr.s_addr = inet_addr(“ 172.16.225.130 ”);

    然后这会导致错误。尝试在我的服务器运行时运行客户端的输出是:

    连接错误:无主机路由

  • 注意:我可以在172.16.225.130从我的主机ping我的虚拟机并成功获得响应。但我无法成功telnet我的VM。它产生相同的“无主机路由”错误。

虚拟机上的服务器代码,IP:172.16.225.130

int main() {

  int sfd, cfd;
  int ch = 'k';
  int optval = 1;
  /* sockaddr_in holds IP address and port info*/
  struct sockaddr_in saddr, caddr;


  sfd = socket(AF_INET, SOCK_STREAM, 0);

  /* set struct sockaddr_in saddr fields */
  saddr.sin_family = AF_INET; /* Set address family to IPv4 Internet */
  saddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any internet address */
  saddr.sin_port = htons(29008); /* Set server port to 29008 */

  setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);

  /* Bind address to the socket (sfd) created */
  bind(sfd, (struct sockaddr *)&saddr, sizeof(saddr));

  listen(sfd, 1);

  while (1) {

        printf("Server waiting...\n");

        cfd = accept(sfd, (struct sockaddr *)NULL, NULL);

        /* Read character from client */
        if (read(cfd, &ch, 1) < 0) perror("read");

        printf("Read character: %c\n from client\n", ch);

        ch++;

        /* Send incremented character to client */
        if (write(cfd, &ch, 1) < 0) perror ("write");

        printf("Sent character: %c\n to client\n", ch);

        /* Close connection with client by closing the client fd */
        close(cfd);
  }

  return 0;
}

我的主机上的客户端代码

int main() {

  int cfd;

  struct sockaddr_in addr;
  char ch = 'r';

  cfd = socket(AF_INET, SOCK_STREAM, 0);

  addr.sin_family = AF_INET;


  addr.sin_addr.s_addr = inet_addr("172.16.225.130");

  addr.sin_port = htons(29008);


  if (connect(cfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
        perror("connect error");
        return -1;
  }


  if (write(cfd, &ch, 1) < 0) perror("write");
  if (read(cfd, &ch, 1) < 0) perror("read");
  printf("nReply from Server: %cnn\n", ch);
  close(cfd);
  return 0;
}

修改 这是我已经尝试过的东西,但仍然无法正常工作。

1. 在我的虚拟机中打开端口29008:

我的/ etc / sysconfig / iptables文件中的附加规则:

-A INPUT -m state --state NEW -m tcp -p tcp --dport 29008 -j ACCEPT

保存并关闭文件。重启iptables:

/etc/init.d/iptables restart

2. :通过配置防火墙设置,彼此接收允许的请求:

在VM上:sudo iptables -A INPUT -s 172.16.225.1 -j ACCEPT

在主机上:sudo iptables -A INPUT -s 172.16.225.130 -j ACCEPT

3. 彻底关闭我的VM上的iptables。这产生了不同的结果。运行我的客户端而不是“无路由到主机”错误,导致它只是挂起。

0 个答案:

没有答案
相关问题