从套接字描述符恢复IP/端口 [英] Recovering IP/Port from Socket Descriptor

查看:114
本文介绍了从套接字描述符恢复IP/端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写 inetd的克隆,其中我必须运行一台服务器,该服务器打印连接到它的客户端的IP和端口.

I'm writing a clone of inetd in which I must run a server that prints the IP and port of the client connecting to it.

当我用套接字描述符覆盖STDINSTDOUT时,我的初始解决方案要执行此操作,是恢复包含所需信息的sockaddr_in结构.但是,使用getsockname()执行此操作将返回一个空结构,所有位都设置为0.

As I overwrite STDIN and STDOUT with the socket descriptor, my initial solution to do this was to recover the sockaddr_in structure, which contains the needed information. Doing this with getsockname(), however, is returning an empty structure, with all bits set to 0.

我的方法有什么问题吗?我还可以使用其他方法来恢复IP/端口吗?

Any idea of what is wrong with my approach? Are there any other approaches I can use to recover the IP/Port?

谢谢

推荐答案

正如R ..指出的那样,您应该使用 getpeername .该函数和 getsockname 都将文件描述符作为其第一个参数,而不是流指针(FILE *).使用fileno(stdin)获取标准输入的文件描述符(或将其硬编码为STDIN_FILENO,因为它是常量).

As R.. pointed out, you should use getpeername. Both that function and getsockname take a file descriptor as its first argument, not a stream pointer (FILE *). Use fileno(stdin) to get the file descriptor for standard input (or hard-code it to STDIN_FILENO, as it's constant).

此外,getsocknamegetpeername的最后一个参数应该是指向socklen_t的指针,而不是常量,并且应该对TCP/IP使用sockaddr_in:

Also, the last argument to getsockname and getpeername should be a pointer to socklen_t, not a constant, and you should use a sockaddr_in for TCP/IP:

struct sockaddr_in peeraddr;
socklen_t peeraddrlen = sizeof(peeraddr);
getpeername(STDIN_FILENO, &peeraddr, &peeraddrlen);

此处中查看完整的示例..

See a complete example here.

这篇关于从套接字描述符恢复IP/端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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