Let's send a message to C-SERVER:
echo '1234567890' | nc <ip> <port>
C-SERVER prints: ( oo.ooo.o = partial IP of client )
678oo.ooo.o---
But I only asked it to print 3 characters from the incoming message.
( starting from 5th character )
strncpy(ii2, iii + 5, 3);
it should only be printing: ( plus the --- )
 678
Question: WHY is it attaching a partial IP address of the client to the string above ?
EXTRA INFO:
The problem seems to go away when I remove this line all together:
snprintf(iip, 15, "%s", inet_ntoa(cli_addr.sin_addr));
But I do not want to remove that line.
FULL CODE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>
#include <string.h>
char * nnn;
char iii [500];
char ii2 [3];
char iip [15];
int main()
{
  int one = 1, client_fd;
  struct sockaddr_in svr_addr, cli_addr;
  socklen_t sin_len = sizeof(cli_addr);
  int sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0)
    err(1, "can't open socket");
  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));
  int port = 86;
  svr_addr.sin_family = AF_INET;
  svr_addr.sin_addr.s_addr = INADDR_ANY;
  svr_addr.sin_port = htons(port);
  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
    close(sock);
    err(1, "Can't bind");
  }
  listen(sock, 5);
  while (1) {
    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
    snprintf(iip, 15, "%s", inet_ntoa(cli_addr.sin_addr));
    ssize_t t = read(client_fd,iii,500);
    if ( t > 0 ) { iii[ t ] = '\0'; ii2[ t ] = '\0'; }
    strncpy(ii2, iii + 5, 3);
    printf(ii2);
    printf("---");
    printf("\n");
    asprintf(&nnn, "%s\n", ii2);
    write(client_fd, nnn, strlen(nnn));
    close(client_fd);
  }
}
 
     
    