c - 如何在 C 中将客户端的 IP 存储在数组中(套接字编程)

标签 c arrays list sockets server

我在 C 语言的套接字中有简单的客户端/服务器程序。我使用 inet_ntoa 返回连接到服务器的客户端的 IP。我运行循环 2 次来连接 2 个客户端,并将 int 存储在 char 数组中。

问题是,当我打印数组时,它总是给出添加到数组中的最后一个 ip。例如:

x.x.x.x connected 
y.y.y.y connected 

数组打印y.y.y.y两次

#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>

#define MAX 80
#define PORT 8080
#define SA struct sockaddr

// Driver function 
int main() {

  int sockfd, connfd, len;
  struct sockaddr_in servaddr, cli;
  struct sockaddr_in addr_remote;
  char * ips[2];
  // socket create and verification 
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd == -1) {
    printf("socket creation failed...\n");
    exit(0);
  } 
  else
    printf("Socket successfully created..\n");
  bzero( & servaddr, sizeof(servaddr));

  // assign IP, PORT 
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(PORT);

  // Binding newly created socket to given IP and verification 
  if ((bind(sockfd, (SA * ) & servaddr, sizeof(servaddr))) != 0) {
    printf("socket bind failed...\n");
    exit(0);
  } 
  else
    printf("Socket successfully binded..\n");

  // Now server is ready to listen and verification 
  int i = 0;
  for (i = 0; i < 2; i++) {
    if ((listen(sockfd, 5)) != 0) {
      printf("Listen failed...\n");
      exit(0);
    } 
    else
      printf("Server listening..\n");
    len = sizeof(cli);

    // Accept the data packet from client and verification 
    connfd = accept(sockfd, (SA * ) & addr_remote, & len);
    if (connfd < 0) {
      printf("server acccept failed...\n");
      exit(0);
    }
    else
      printf("server acccept the client...\n");

    // Function for chatting between client and server 
    // func(connfd); 
    //printf( " Welcome %s " , inet_ntoa(addr_remote.sin_addr));
    ips[i] = inet_ntoa(addr_remote.sin_addr);

  }
  for (i = 0; i < 2; i++) {

    printf("%s", ips[i]);

  }
  // After chatting close the socket 
  close(sockfd);
}

最佳答案

您必须为 IP 分配自己的字符数组,并从 inet_ntoa() 返回的静态缓冲区中复制它。简单的例子:

char ips[2][20];
...
strcpy(ips[i], inet_ntoa(...))

编辑:重点是,inet_ntoa()函数将其结果存储到其内部、静态分配的缓冲区中,并仅返回指向它的指针,该指针是常量。因此,您的 ip[0]ip[1] 都包含相同的指针,该指针指向从 inet_ntoa() 获取的最后一个 IP。

关于c - 如何在 C 中将客户端的 IP 存储在数组中(套接字编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55573854/

相关文章:

c - 如何将不同的元素插入数组?

c - Cygwin 中的段错误和默认变量初始化

python - numpy 列数组和奇怪的结果

python - 在python中合并字典值列表

python - 一个类轮 : creating a dictionary from list with indices as keys

python - 为什么即使列表在内存中移动,列表的 id 也不会改变?

c - Matlab 在 Mex 文件中的 fopen 上崩溃

从 char * 复制到 char 数组

python - 在循环中同时对数组的数组的数组进行操作python

javascript - JavaScript 中的多个 IF 和 ELSE IF