【问题标题】:Connecting two computer via socket, in c and on linux在c和linux上通过socket连接两台计算机
【发布时间】:2021-06-24 04:17:41
【问题描述】:

我用 C 语言创建了一个服务器,可以通过 telnet (telnet localhost 8000) 与它通信,它可以在我的计算机上按预期工作。 我想从连接在同一网络上的另一台计算机上工作。我尝试将在www.myip.com 上找到的公共 ip 和主机代替本地主机,但它没有用。 这是我的服务器。c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>

#define PORT "8000" // the port users will be connecting to

#define BACKLOG 10 // how many pending connections queue will hold

void sigchld_handler(int s)
{
    // waitpid() might overwrite errno, so we save and restore it:
    int saved_errno = errno;

    while (waitpid(-1, NULL, WNOHANG) > 0)
        ;

    errno = saved_errno;
}

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET)
    {
        return &(((struct sockaddr_in *)sa)->sin_addr);
    }

    return &(((struct sockaddr_in6 *)sa)->sin6_addr);
}

int main(void)
{
    int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    struct sigaction sa;
    int yes = 1;
    char s[INET6_ADDRSTRLEN];
    int rv;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0)
    {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for (p = servinfo; p != NULL; p = p->ai_next)
    {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                             p->ai_protocol)) == -1)
        {
            perror("server: socket");
            continue;
        }

        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
                       sizeof(int)) == -1)
        {
            perror("setsockopt");
            exit(1);
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
        {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    freeaddrinfo(servinfo); // all done with this structure
    if (p == NULL) {
        fprintf(stderr, "server: failed to bind\n");
        exit(1);
    }
    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }
    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }
    printf("server: waiting for connections...\n");
    while (1)
    { // main accept() loop
        sin_size = sizeof their_addr;
        new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if (new_fd == -1)
        {
            perror("accept");
            continue;
        }

        inet_ntop(their_addr.ss_family,
                  get_in_addr((struct sockaddr *)&their_addr),
                  s, sizeof s);
        printf("server: got connection from %s\n", s);
        char myBuff[200];
        if (!fork())
        {
            while (1) {
            memset(myBuff, 0, 200);
            close(sockfd); // child doesn't need the listener
            if (send(new_fd, "Hello!\n", 8, 0) == -1)
                perror("send");
            recv(new_fd, myBuff, 200, 0);
            printf("%s", myBuff);
            }
        }
        close(new_fd); // parent doesn't need this
    }
    return 0;
}

【问题讨论】:

  • 通常的:(您必须正确且完整地处理从系统调用(如recv())返回的结果。您必须确保“字符串”库调用通过有保证的以NUL 结尾的字符数组。
  • '但是没有用'......什么测试失败了,怎么失败的?

标签: c sockets networking


【解决方案1】:

我认为您的问题不在于代码本身,而更多是网络问题...

首先,我会通过运行netstat -ln | grep 8000 检查您的服务器是否正在侦听所有地址。如果它返回一个特定地址(例如,192.168.0.176:8000),那么这就是您应该连接的 IP。但是由于您已经从 localhost 进行了连接,我想您会找到类似 0.0.0.0:8000*:8000 的内容(我不记得现在在 linux 中的确切格式)。

如果您找到的 IP 是 0.0.0.0,并且您想从同一本地网络中的计算机连接,则不应使用公共 IP,因为这是您路由器的 IP(实际上,您可以检查两台计算机的公共 IP 可能相同,因为它们共享路由器)。这样做是可能的,但它很可能需要端口转发,以便路由器知道它应该向哪个 IP 发送端口 8000 的连接尝试。

你应该在你的服务器中执行ifconfig | grep "inet "。这将返回服务器正在侦听的 IP 地址列表。如果您在客户端执行相同的命令,您会发现其中至少有一个非常相似(例如,服务器中的192.168.0.176 和客户端中的192.168.0.178)。然后,您应该尝试在 telnet 命令中使用您在服务器中找到的 IP 地址。

如果这不起作用,很可能是服务器中的防火墙阻止了与服务器中该端口的连接。您应该尝试打开该端口并再次检查。

【讨论】:

  • 感谢您的分析,我得到了一个“没有路由到主机”的错误,现在我认为它与防火墙有关
猜你喜欢
  • 1970-01-01
  • 2018-05-28
  • 2017-05-08
  • 1970-01-01
  • 2019-08-09
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-03
相关资源
最近更新 更多