Sockets working in openSUSE do not work in Debian?

試著忘記壹切 提交于 2019-12-08 06:28:10

问题


I have a C/C++ TCP client working in OpenSUSE but not in Debian. I'm using nc -l 4242 for the server. Then I connect with ./my_client 127.0.0.1 4242 on my Debian system (Sid) and it will fail when using the connect function.

Can you confirm if you have the same error too, using Debian or maybe another OS? Where does the problem come from?

Here's the code:

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>

void do_server(int s)
{
  write(s, "client connected\n", strlen("client connected\n"));
  close(s);
}

int main(int ac, char **av)
{
  struct protoent *pe;
  struct sockaddr_in sin;
  int s;

  if (ac != 3)
    {
      std::cerr << "Usage: ./client ip port" << std::endl;
      return EXIT_FAILURE;
    }
  pe = getprotobyname("TCP");
  if ((s = socket(AF_INET, SOCK_STREAM, pe->p_proto)) == -1)
    {
      std::cerr << "Error: socket" << std::endl;
      return EXIT_FAILURE;
    }
  sin.sin_family = AF_INET;
  sin.sin_port = htons(atoi(av[2]));
  sin.sin_addr.s_addr = inet_addr(av[1]);
  if (connect(s, (const struct sockaddr *)&sin, sizeof(sin)) == -1)
    {
      std::cerr << "Error: connect" << std::endl;
      close(s);
      return EXIT_FAILURE;
    }
  std::cout << "client started" << std::endl;
  do_server(s);
  return EXIT_SUCCESS;
}

回答1:


This seems to have to do with the netcat flavor you have selected.

With the 'traditional' netcat (/etc/alternatives/nc links to /bin/nc.traditional) you have to use this syntax to specify the listening port:

nc -l -p 4242

The 'openbsd' netcat also supports this syntax (as well as the one you used) even though it's man page says you can't use -l and -p together.



来源:https://stackoverflow.com/questions/15318164/sockets-working-in-opensuse-do-not-work-in-debian

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!