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

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

问题描述

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

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

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

谢谢

解决方案

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

另外,getsocknamegetpeername 的最后一个参数应该是一个指向 socklen_t 的指针,而不是一个常量,你应该使用 <代码>sockaddr_in 用于 TCP/IP:

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

此处查看完整示例.>

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.

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.

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

Thanks

解决方案

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).

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天全站免登陆