title: linux C server - identifying / naming the client
body: <p>By hostname, I mean the name of the PC of the client.</p>
  
  <p>I'm trying to identify each of the connected client of the server.<br>
  Like client -> server. Server says: <code>client hostname has connected.</code><br>
  then all the process by that client will be tagged with the hostname.
  And I don't really know how to.</p>
  
  <p>My client code:</p>
  
  <pre><code>char hostname[1024];
  
  gethostname(hostname, 1023);
  send(sock, hostname, hostname, 0);
  //now we are done sending the hostname of the client.
  </code></pre>
  
  <p>My server code (the loop):</p>
  
  <pre><code>void clients (int sock)
  {
      int n, p;
      char buffer[256];
      char request;
      FILE *file; 
      file = fopen("process.log","a+");
  
  
      //the stuff i added for the identification 
      char hostbuf[256];
      bzero(hostbuf,256);
      n = read(sock,hostbuf,255);
              printf("%s has connected.\n",buffer);
  
  
      //after the client has been identified then we tag all communications from that client as its hostname/identification.
  
      do
      {
      bzero(buffer,256);
      p = read(sock,buffer,255);
      if (p &lt; 0) error("ERROR reading from socket");
  
      //the output i modified
      printf("%s sent: %s\n",hostbuf,buffer);
  
      n = write(sock,buffer,sizeof(buffer));
  
      if (n &lt; 0) error("ERROR writing to socket");
      fprintf(file,"%s\n",buffer); /*writes*/ 
  
      }while(p == 11);
  
      fclose(file);
  }
  </code></pre>
  
  <p>----------- edit -----------</p>
  
  <p>Used both suggestions together</p>
  
  <p>Added to code:</p>
  
  <pre><code>socklen_t len;
  struct sockaddr_storage addr;
  char ipstr[INET_ADDRSTRLEN];
  int port;
  
     len = sizeof addr;
     getpeername(sock, (struct sockaddr*)&amp;addr, &amp;len);
  
     // deal with both IPv4 and IPv6:
  if (addr.ss_family == AF_INET) {
    struct sockaddr_in *s = (struct sockaddr_in *)&amp;addr;
    port = ntohs(s-&gt;sin_port);
    inet_ntop(AF_INET, &amp;s-&gt;sin_addr, ipstr, sizeof ipstr);
  } else { // AF_INET6
    struct sockaddr_in6 *s = (struct sockaddr_in6 *)&amp;addr;
    port = ntohs(s-&gt;sin6_port);
   inet_ntop(AF_INET6, &amp;s-&gt;sin6_addr, ipstr, sizeof ipstr);
  }
  
  
  char host[1024];
  
     getnameinfo(&amp;addr, sizeof addr, host, sizeof host, NULL, NULL, 0);
  </code></pre>
  
  <p>tried to display it:</p>
  
  <pre><code>printf("%s has connected from %s.", host,ipstr);
      //returned 'myip.myisp.net has connected from *.*.*.*.'
      //i want it to return my PC name.
      //my pc name is SashaGre-PC :))
  </code></pre>
  
  <p>It works but it doesn't return my PC name but rather the 'ip.ispdomain.net'.</p>