Linux under the Getsockopt/setsockopt function Description _ Android

Source: Internet
Author: User
Tags socket error htons
Linux below getsockopt/setsockopt function description

"Getsockopt/setsockopt system call"

Function Description:
Gets or sets the options associated with a socket. Options may exist in multi-tier protocols, and they always appear on the topmost sockets layer. When you manipulate socket options, the names of the layers and options at which the options are located must be given. In order to manipulate the options for the sockets layer, the value of the layer should be specified as Sol_socket. The appropriate protocol number for the control option must be given in order to operate the other layer's options. For example, to indicate that an option is resolved by the TCP protocol, the layer should be set to protocol number TCP.


Usage:
#include <sys/types.h>
#include <sys/socket.h>

int getsockopt (int sock, int level, int optname, void *optval, socklen_t *optlen);

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

Parameters:
Sock: The socket that will be set or get the option.
Level: The protocol layer at which the option resides.
Optname: The option name that needs to be accessed.
Optval: For GetSockOpt (), point to a buffer that returns the value of the option. For setsockopt (), point to the buffer that contains the new option value.
Optlen: For GetSockOpt (), the maximum length of the option value as the entry parameter. The actual length of the option value as an exit parameter. For setsockopt (), the length of the current option.


Return Description:
When successfully executed, returns 0. Failure returns -1,errno is set to one of the following values
Ebadf:sock is not a valid file descriptive word
Efault:optval point to memory is not a valid process space
Einval: Optlen is not valid when setsockopt () is invoked
ENOPROTOOPT: The specified protocol layer does not recognize the option
Enotsock:sock is not describing a socket

First you know that the KeepAlive property of the setsockopt () function is to test periodically whether the connection is still alive,
I looked up a lot of information on the Internet or didn't know how to use it.
Finally bite the bullet himself wrote a server-side and a client socket connection
Set the KeepAlive property on both ends to open
Server side:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <error.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>

#define SERVPORT 6000//Set Server service port to 6000
#define MAX_LISTEN_SOCK_NUM 20//Set the maximum number of listening sockets is 20
int main ()
{
SOCKFD is the local listener socket identifier, CLIENT_FD is the client socket identifier
int sockfd,client_fd;
struct sockaddr_in my_addr;
struct sockaddr_in client_addr;

Create a local listening socket
if ((Sockfd=socket (af_inet,sock_stream,0)) ==-1) {
Perror ("Socket creation failed!/n");
Exit (1);
}

Set the properties of the socket to enable it to reuse the socket's ports and IP when the computer restarts
int err,sock_reuse=1;
Err=setsockopt (SOCKFD,SOL_SOCKET,SO_REUSEADDR, (char *) &sock_reuse,sizeof (sock_reuse));
if (err!=0) {
printf ("Socket reusable settings failed!/n");
Exit (1);
}
My_addr.sin_family=af_inet;
My_addr.sin_port=htons (Servport);
My_addr.sin_addr.s_addr=inaddr_any;
Bzero (& (My_addr.sin_zero), 8);
Binding sockets
if (Bind (SOCKFD, (struct sockaddr *) &my_addr,sizeof (struct sockaddr)) ==-1) {
Perror ("Bind failed!/n");
Exit (1);
}
Set up listening
if ((Listen (sockfd,max_listen_sock_num)) ==-1) {
Perror ("Set listening failure!/n");
Exit (1);
}
printf ("Sockets Enter the listening state, waiting for a request connection:/n");

int time_to_quit=1;
while (time_to_quit) {//Can be set Time_to_quit to actively shut down the server side
while (1) {

Connect when a connection request is made
socklen_t sin_size=sizeof (struct sockaddr_in);
if ((Client_fd=accept (SOCKFD, struct sockaddr *) &client_addr,&sin_size)) ==-1) {
Perror ("Accept connection Failure!/n");
Continue
}

int opt;
socklen_t len=sizeof (int);
if ((GetSockOpt (sockfd,sol_socket,so_keepalive, (char*) &opt,&len)) ==0) {
printf ("So_keepalive Value:%d/n", opt);
}
printf ("Receive a connection from%s/n", Inet_ntoa (CLIENT_ADDR.SIN_ADDR));
Create a subprocess to process connected client sockets

if (Send (CLIENT_FD, "Hello, you have connected successfully!/n", 50,0) ==-1) {
Perror ("Send notification information failed!/n");
Exit (0);
}

}
Close (CLIENT_FD);

return 0;
}
Client:
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#define MAXDATASIZE 100/* Maximum data transfer per time * *
int main ()
{
int sockfd,nbytes,serv_port;
Char buf_serv_ip[16],buf[26];
struct sockaddr_in serv_addr;
if ((Sockfd=socket (af_inet,sock_stream,0)) ==-1) {
Perror ("Create socket failed!/n");
Exit (1);
}
To set its reusable properties after a socket has been created successfully
int keepalive=1;
socklen_t kplen=sizeof (int);
if (setsockopt (sockfd,sol_socket,so_keepalive, (char *) &keepalive,kplen)!=0) {
Perror ("Set cycle test connection is still alive failure!/n");
Exit (1);
}
printf ("Please enter the IP address to connect to the host:/n");
scanf ("%s", buf_serv_ip);
printf (Please enter the port number to connect to the host:/n);
scanf ("%d", &serv_port);
Serv_addr.sin_family=af_inet;
SERV_ADDR.SIN_ADDR.S_ADDR=INET_ADDR (BUF_SERV_IP);
Serv_addr.sin_port=htons (Serv_port);
Bzero (& (Serv_addr.sin_zero), 8);
if (Connect (SOCKFD, (struct sockaddr *) &serv_addr,sizeof (struct sockaddr)) ==-1) {
Perror ("Connection Server failed!/n");
Exit (1);
}
printf ("Connect the server successfully!/n");
Here you can take a look at the length of the data to be accepted before you create an array
if ((Nbytes=recv (sockfd,buf,26,0)) ==-1) {
Perror ("Accept data failure!/n");
Exit (1);
}
Buf[nbytes]= '/0 ';
printf ("Accepted Data:%s/n", buf);
Close (SOCKFD);
return 0;
}
Two terminals shipped (on the same host) line: First start the server side, then start the client, to the server-side request connection, after the successful connection, the client socket closed, server-side socket always open, wait two hours more also did not respond,

Ken asked the expert to guide:
(1) Does this result in the expectation that the connection is still present?
(2) What should not be done,
(3) also has getsockopt () the related function is what. This function is not used in the program above
(4) Read the UNIX network programming a little bit about the explanation of the problem still do not understand, because she mentioned that it takes two hours to respond, but waited for the hour did not respond, she also said that can shorten the time, I do not know how to shorten the getsockopt and setsockopt

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)

level specifies the hierarchy of the control sockets. You can take three values:
1) Sol_socket: Universal socket option.
2) ipproto_ip:ip option.
3) ipproto_tcp:tcp option.
Optname Specify the mode of control (the name of the option), we explain in detail below

Optval Gets or sets the socket option. Conversion based on the data type of the option name


Option Name Description Data type
========================================================================
Sol_socket
------------------------------------------------------------------------
SO_BROADCAST allows broadcast data int to be sent
So_debug allows you to debug int
So_dontroute does not find route int
So_error Get socket Error int
So_keepalive remain connected int
So_linger delay close connection struct linger
So_oobinline Out-of-band data into normal data flow int
SO_RCVBUF Receive buffer size int
SO_SNDBUF Send buffer size int
So_rcvlowat receive buffer lower bound int
So_sndlowat send buffer lower bound int
So_rcvtimeo Receive timeout struct timeval
So_sndtimeo Send timeout struct timeval
SO_REUSERADDR allows reuse of local address and Port int
So_type Get socket type int
So_bsdcompat and BSD Systems compatible int
========================================================================
Ipproto_ip
------------------------------------------------------------------------
IP_HDRINCL contains IP header int in the packet
Ip_optinos IP Header option int
Ip_tos Service Type
Ip_ttl Time to live int
========================================================================
Ippro_tcp
------------------------------------------------------------------------
Tcp_maxseg the size of the TCP maximum data segment int
Tcp_nodelay does not use the Nagle algorithm int
========================================================================

Return Description:
When successfully executed, returns 0. Failure returns -1,errno is set to one of the following values
Ebadf:sock is not a valid file descriptive word
Efault:optval point to memory is not a valid process space
Einval: Optlen is not valid when setsockopt () is invoked
ENOPROTOOPT: The specified protocol layer does not recognize the option
Enotsock:sock is not describing a socket

So_rcvbuf and So_sndbuf Each set of interfaces have a send buffer and a receive buffer, using these two sets of interface options to change the default buffer size.

Receive Buffer
int nrecvbuf=32*1024; Set to 32K
SetSockOpt (S,sol_socket,so_rcvbuf, (const char*) &nrecvbuf,sizeof (int));

Send buffer
int nsendbuf=32*1024;//set to 32K
SetSockOpt (S,sol_socket,so_sndbuf, (const char*) &nsendbuf,sizeof (int));

Attention:

The order of function calls is important when setting the size of the TCP socket receive buffer, because the window size option for TCP is to be interchanged with the other when establishing a connection. For customers, the SO_RCVBUF option must be set before connect, and for the server, the SO_RCVBUF option must be set before listen.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.