gpt4 book ai didi

c - linux C 服务器 - 识别/命名客户端

转载 作者:太空狗 更新时间:2023-10-29 11:29:53 26 4
gpt4 key购买 nike

主机名是指客户端 PC 的名称。

我正在尝试识别服务器的每个已连接客户端。
像客户端-> 服务器。服务器说:客户端主机名已连接。
那么该客户端的所有进程都将被标记为主机名。我真的不知道该怎么做。

我的客户端代码:

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”。

最佳答案

此外,如果您想要客户端的主机名,每次您在accept 中获得新的客户端连接时,从服务器使用getnameinfo。这里有例子: https://beej.us/guide/bgnet/html/multi/getnameinfoman.html

对于 Windows:http://msdn.microsoft.com/en-us/library/windows/desktop/ms738532(v=vs.85).aspx

关于c - linux C 服务器 - 识别/命名客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13552758/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com