How do I store client's IPs in array in C (socket programming)

时间:2019-04-08 12:46:53

标签: c arrays list sockets server

I have simple client/server program in socket in C. I use inet_ntoa that returns ip of clients connected to servers. I run a loop 2 times to connect 2 clients and store int in array of char.

The problem is that when I print the array it always gives the last ip added to the array. For example:

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

The array prints y.y.y.y two times

#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);
}

1 个答案:

答案 0 :(得分:1)

You have to allocate Your own char array for IP and copy it from static buffer returned by inet_ntoa(). Simple example:

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

EDIT: The point is, that the inet_ntoa() function stores it's result to it's internal, statically allocated, buffer and returns just a pointer to it, which is constant. So Your ip[0] and ip[1] both contain the same pointer, which points to the last IP obtained from inet_ntoa().