如何从另一台计算机和网络访问我的 C 语言套接字服务器?

How to access my socket server in C language from another computer and network?

我有一个 C 套接字侦听本地主机上的端口 1001。我还有连接到 IP 127.0.0.1 上的端口 1001 的客户端代码。如果我将客户的代码发送给我的朋友,当我们在不同的网络上时他怎么能访问我的机器?我是否可以仅通过更改服务器代码使我的 public IP 为端口 1001 上的连接打开?下面是简单的服务器代码:

obs:我在学C

    #include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define BUFSIZE 256

short SocketCreate(void)
{
  short hSocket;
  printf("Create the socket\n");

  hSocket = socket(AF_INET, SOCK_STREAM, 0);
  // close(hSocket);
  return hSocket;
}

int BindCreatedSocket(int hSocket)
{
  int iRetval = -1, ClientPort = 1001;
  struct sockaddr_in remote = {0};

  remote.sin_family = AF_INET;
  remote.sin_addr.s_addr = htonl(INADDR_ANY);
  remote.sin_port = htons(ClientPort);
  iRetval = bind(hSocket, (struct sockaddr *)&remote, sizeof(remote));

  return iRetval;
}

int main(int argc, char *argv[])
{
  int socket_desc, sock, clientLen;
  struct sockaddr_in client;
  char client_message[200] = {0}, message[9999] = {0};

  char buf[BUFSIZE];

  socket_desc = SocketCreate();
  if (socket_desc == -1)
  {
    printf("Could not create socket");
    return 1;
  }
  printf("Socket created\n");

  if (BindCreatedSocket(socket_desc) < 0)
  {
    perror("bind failed.");
    return 1;
  }

  printf("Waiting for incoming connections...\n");

  listen(socket_desc, 3);

  while (1)
  {
    clientLen = sizeof(struct sockaddr_in);

    sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t *)&clientLen);
    if (sock < 0)
    {
      perror("accept failed");
      return 1;
    }
    // printf("Connection accepted\n");

    memset(client_message, '[=10=]', sizeof(client_message));
    memset(message, '[=10=]', sizeof(message));

    if (recv(sock, client_message, 200, 0) < 0)
    {
      printf("recv failed");
      break;
    }

    if (strcmp(client_message, "exitserver") == 0)
    {
      close(socket_desc);
      close(sock);
      break;
    }
  }
  return 0;
}

I have a C socket that listens on port 1001 on localhost. I also have the client code that connects to port 1001 on the ip 127.0.0.1. If I send the client's code to my friend, how could he have access to my machine when we would be on different networks?

他们做不到。地址 127.0.0.1 是一个 loopback 地址。发送到该地址的数据包总是定向到发送它们的机器。

Is it possible for me just by changing the server code to make my public IP open for connections on port 1001?

public IP 吗? 127.0.0.1 肯定不是一个,大多数拥有 consumer-grade 互联网服务的人都没有。如果您确实拥有一个,您可能必须做出特殊安排才能获得它,并且您可能需要为此特权支付额外费用。

但是假设您确实有一个 public IP 或者您已安排获得一个 IP,不,您不能确保通过您的服务器程序打开端口。您的程序可以毫不费力地侦听该地址,但您还必须考虑防火墙——可能一个在您的本地机器上,一个在您的本地路由器上,至少。

此外,在设置 public 服务器之前,您最好检查一下您的 ISP 的政策和用户协议。 ISP 禁止消费者互联网连接上的 运行 outward-facing 服务的情况并不少见。他们通常希望您为该特权支付更多费用,这也使 ISP 更容易监管他们的网络。