开发者

about setsockopt() and getsockopt() function

for what especially the socket option开发者_JAVA技巧s are used i.e setsockopt() and getsockopt() in socket programming ?


For example you want to set or know receive buffer size

1)

int skt, int sndsize;
err = setsockopt(skt, SOL_SOCKET, SO_RCVBUF, (char *)&sndsize,
                                 (int)sizeof(sndsize));

err = getsockopt(skt, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, &size);

2) Reuse address

 int on = 1;
 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)


For many different things including changing the size of send and receive buffers, length of timeouts, multicasting, keeping the connection alive, disabling Nagel algorithm, etc.

There are levels of options depending on what network layer you what to interact with: socket itself, IP, TCP, and so forth.


As already mentioned they are used for setting/getting various options for a socket.

For example, if you are testing a server application that crashes, you don't wont to wait a certain number of minutes before the kernel let you reuse the port avoiding the "Address already in use" error messages. This can be avoided if you use the SO_REUSEADDR option, letting other sockets to bind to the same port unless there is an active listener bound already.

You can also retrieve data about a socket, such as the number of lost packets / retransmissions etc by using the TCP_INFO on linux machines.

Basically, you can configure all the fine settings.

Options for setsockopt(2) and getsockopt(2).


Superficially, sockets look like a bidirectional pipe which is useful because standard system calls such as write, read, close can be used on them just like on normal pipes or even files. Even if you add socket-specific calls (listen, connect, bind, accept), there is a useful level of abstraction that hides away details in favor of the notion of streaming or datagram sockets.

But as soon as protocol-specific details come into play and specific settings need to be tuned (for example send/receive buffers, timeout settings), a very generic interface is needed to account for the different settings and their specific data formats. getsockopt, setsockopt are part of this generic interface.

int getsockopt(int sockfd, int level, int optname,
               void *optval, socklen_t *optlen);
int setsockopt(int sockfd, int level, int optname,
               const void *optval, socklen_t optlen);

The protocol-specific options are selected using level and optname and the protocol-specific data is hidden in a buffer, so the two system calls do not need to know anything about the settings of every protocol the OS may support -- it's enough if your application and the actual protocol implementation know about those details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜