By hostname, I mean the name of the PC of the client.
I'm trying to identify each of the connected client of the server.
Like client -> server. Server says: client hostname has connected.
then all the process by that client will be tagged with the hostname.
And I don't really know how to.
My client code:
char hostname[1024];
gethostname(hostname, 1023);
send(sock, hostname, hostname, 0);
//now we are done sending the hostname of the client.
My server code (the loop):
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 < 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 < 0) error("ERROR writing to socket");
fprintf(file,"%s\n",buffer); /*writes*/
}while(p == 11);
fclose(file);
}
----------- edit -----------
Used both suggestions together
Added to code:
socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET_ADDRSTRLEN];
int port;
len = sizeof addr;
getpeername(sock, (struct sockaddr*)&addr, &len);
// deal with both IPv4 and IPv6:
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}
char host[1024];
getnameinfo(&addr, sizeof addr, host, sizeof host, NULL, NULL, 0);
tried to display it:
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 :))
It works but it doesn't return my PC name but rather the 'ip.ispdomain.net'.