主机名是指客户端 PC 的名称。
我正在尝试识别服务器的每个连接的客户端。
像客户端->服务器。服务器说:client hostname has connected.
那么该客户端的所有进程都将使用主机名进行标记。我真的不知道该怎么做。
我的客户代码:
char hostname[1024];
gethostname(hostname, 1023);
send(sock, hostname, hostname, 0);
//now we are done sending the hostname of the client.
我的服务器代码(循环):
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);
}
- - - - - - 编辑 - - - - - -
一起使用了这两个建议
添加到代码中:
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);
试图显示它:
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 :))
它可以工作,但它不会返回我的 PC 名称,而是返回“ip.ispdomain.net”。