(如何)我可以从套接字文件描述符中确定套接字系列 [英] (How) Can I determine the socket family from the socket file descriptor

查看:106
本文介绍了(如何)我可以从套接字文件描述符中确定套接字系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个API,其中包含IPC函数,这些函数会将数据发送到可能位于本地或另一主机上的另一个进程.我真的希望send函数像这样简单:

I am writing an API which includes IPC functions which send data to another process which may be local or on another host. I'd really like the send function to be as simple as:

int mySendFunc(myDataThing_t* thing, int sd);

调用者不必知道-在mySendFunc()调用的直接上下文中-sd是导致本地进程还是远程进程.在我看来,如果可以的话:

without the caller having to know -- in the immediate context of the mySendFunc() call -- whether sd leads to a local or remote process. It seems to me that if I could so something like:

switch (socketFamily(sd)) {
case AF_UNIX:
case AF_LOCAL:
   // Send without byteswapping
   break;
default:
   // Use htons() and htonl() on multi-byte values
   break;
}

有人建议我可以将socketFamily()实现为:

It has been suggested that I might implement socketFamily() as:

unsigned short socketFamily(int sd)
{
   struct sockaddr sa;
   size_t len;
   getsockname(sd, &sa, &len);   
   return sa.sa_family;
}

但是我有点担心getsockname()的效率,想知道我每次发送时是否能负担得起.

But I'm a little concerned about the efficiency of getsockname() and wonder if I can afford to do it every time I send.

推荐答案

请参见 getsockname(2 ).然后,您检查该家族的 struct sockaddr .

See getsockname(2). You then inspect the struct sockaddr for the family.

作为旁注,它有时对查询 info 也是有用的,在这种情况下, info libc套接字

As a side note, its sometimes useful to query info as well, in this case info libc sockets

您真的不知道是否每次都不知道.不能简单地缓存它,因为套接字号可以通过关闭和重新打开来重新使用.我只是查看了glibc代码,似乎 getsockname 仅仅是一个系统调用,在性能上可能令人讨厌.

You really can't know without looking it up every time. It can't be simply cached, as the socket number can be reused by closing and reopening it. I just looked into the glibc code and it seems getsockname is simply a syscall, which could be nasty performance-wise.

但是我的建议是使用某种面向对象的概念.让用户传递指向您先前返回给他的结构的指针,即让他使用您的API注册/打开套接字.然后,您可以缓存该套接字的任何内容.

But my suggestion is to use some sort of object-oriented concepts. Make the user pass a pointer to a struct you had previously returned to him, i.e. have him register/open sockets with your API. Then you can cache whatever you want about that socket.

这篇关于(如何)我可以从套接字文件描述符中确定套接字系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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