C套接字从接受返回的文件描述符中获取IP地址 [英] C socket get IP address from filedescriptor returned from accept

查看:75
本文介绍了C套接字从接受返回的文件描述符中获取IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题似乎很典型,并且已多次回答,但我认为如果您阅读了详细信息,它并不那么普遍(我没有找到).

I know this question seems typical and multiple times answered but I think if you read the details it is not so common (I did not find it).

关键是我正在用c开发 unix服务以打开套接字并等待连接,当我建立连接时,我创建一个处理它的新过程 >,因此可以同时打开多个连接.

The point is that I am developing a unix service in c that opens a socket and waits for connections, when I have a connection I create a new process to treat it, so there can be multiple connections opened at the same time.

int newfd = accept(sockfd, (struct sockaddr *)&clientaddr, (socklen_t*)&clientaddr_size);

稍后(在某些其他方法之后和之内和代码)子进程将连接信息保存到BBDD,我也需要 ,以获取打开该连接的IP地址.

Later on (after and inside some other methods and code) the child process save the connection information to the BBDD and I need also, in that precise moment, to get the IP address that opened that connection being treated.

由于可以同时存在多个连接,并且我传递给accept方法的变量struct sockaddr_in clientaddr 对于所有过程都是共享的我不确定以后再通过这种方式获取IP地址信息是一个好主意,因为这样我可以从打开的另一个连接中获取IP地址.

As there can be multiple connections at the same time and the variable struct sockaddr_in clientaddr that I pass to the accept method is shared for all the process I am not sure that later on is a good idea to get the IP address information from that way because then I could get the IP address from another connection opened.

我希望能够从我从accept方法获得的文件描述符int newfd中访问IP地址(返回的整数).是否有可能?还是我误解了文件描述符功能?

I would like to be able to access the IP address from the file descriptor int newfd that I get from the accept method (the returned integer). Is it possible? Or I misunderstood the file descriptor function?

推荐答案

好.感谢@alk和@rileyberton,我找到了可以使用的正确方法, getpeername :

Ok. Thanks to @alk and @rileyberton I found the correct method to use, the getpeername:

int sockfd;

void main(void) {
    //[...]
    struct sockaddr_in clientaddr;
    socklen_t clientaddr_size = sizeof(clientaddr);
    int newfd = accept(sockfd, (struct sockaddr *)&clientaddr, &clientaddr_size);
    //fork() and other code
    foo(newfd);
    //[...]
}
void foo(int newfd) {
    //[...]
    struct sockaddr_in addr;
    socklen_t addr_size = sizeof(struct sockaddr_in);
    int res = getpeername(newfd, (struct sockaddr *)&addr, &addr_size);
    char *clientip = new char[20];
    strcpy(clientip, inet_ntoa(addr.sin_addr));
    //[...]
}

因此,现在在另一个过程中,我可以获取发起连接的客户端的IP地址(在字符串" clientip中),该客户端仅携带通过accept方法获得的文件描述符newfd.

So now in a different process I can get the IP address (in the "string" clientip) of the client that originated the connection only carrying the file descriptor newfd obtained with the accept method.

这篇关于C套接字从接受返回的文件描述符中获取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆