(How) Can I determine the socket family from the socket file descriptor

前端 未结 3 891
忘了有多久
忘了有多久 2021-01-02 20:02

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 simpl

3条回答
  •  温柔的废话
    2021-01-02 20:48

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

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

    EDIT:

    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.

    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.

提交回复
热议问题