Linux network programming functions

Source: Internet
Author: User

Socket ()

We use the system to call socket () to obtain the file descriptor:
# Include <sys/types. h>
# Include <sys/socket. h>
Int socket (INT domain, int type, int Protocol );
Set the first parameter domain to "af_inet ".
The second parameter is the set interface type: sock_stream or
Sock_dgram. The third parameter is set to 0.
The system calls socket () and returns only one set of interface descriptors. If an error occurs,-1 is returned.

 

BIND ()

Once you have an interface set, the next step is to bind the interface set to a port on the local computer. However, it is unnecessary if you only want to use connect.
The following is how the system calls BIND:
# Include <sys/types. h>
# Include <sys/socket. h>
Intbind (INT sockfd, struct sockaddr * my_addr, int addrlen );
The first parameter sockfd is the set of interface file descriptors returned by the socket () call.
The second parameter my_addr is a pointer to the sockaddr data structure. The data structure sockaddr contains information about your address, port, and IP address.
The third parameter addrlen can be set to sizeof (structsockaddr ).
The following is an example:
# Include <string. h>
# Include <sys/types. h>
# Include <sys/socket. h>
# Define myport 3490
Main ()
{
Int sockfd;
Struct sockaddr_inmy_addr;
Sockfd = socket (af_inet, sock_stream, 0 );
My_addr.sin_family = af_inet;
My_addr.sin_port = htons (myport );
My_addr.sin_addr.s_addr = inet_addr ("132.241.5.10 ");
Bzero (& (my_addr.sin_zero), 8 );

BIND (sockfd, (struct sockaddr *) & my_addr, sizeof (struct sockaddr ));
...
If an error occurs, BIND () also returns-1.
If you use the connect () system call, you do not have to know the port number you are using. When you call connect (), it checks whether the set interface is bound. If not, it will allocate an idle port.

Connect ()

The usage of System Call connect () is as follows:
# Include <sys/types. h>
# Include <sys/socket. h>
Int connect (INT sockfd, struct sockaddr * serv_addr, int addrlen );
The first parameter is the interface file descriptor, Which is returned by the system calling socket.
The second parameter is serv_addr, which is a pointer to the sockaddr data structure, including the destination port and IP address.
The third parameter can be obtained using sizeof (structsockaddr.
The following is an example:
# Include <string. h>
# Include <sys/types. h>
# Include <sys/socket. h>
# Define dest_ip "132.241.5.10"
# Define dest_port 23
Main ()
{
Intsockfd;
Structsockaddr_indest_addr;
Sockfd = socket (af_inet, sock_stream, 0 );
Dest_addr.sin_family = af_inet;
Dest_addr.sin_port = htons (dest_port );
Dest_addr.sin_addr.s_addr = inet_addr (dest_ip );
Bzero (& (dest_addr.sin_zero), 8 );

Connect (sockfd, (structsockaddr *) & dest_addr, sizeof (struct sockaddr ));
...
Similarly, if an error occurs, connect () returns-1.


Listen ()

If you want to not connect to a remote host, that is, you want to wait for a connection request and then process it. In this way, you first call listen () and then call accept.
The listen () method called by the system is as follows:
INTl isten (INT sockfd, int backlog );
The first parameter is the set of interface file descriptors returned by the system to call socket.
The second parameter indicates the number of connections allowed in the queue. The incoming connection request must wait in the queue before the system calls the accept () response. This value is the maximum number of requests in the queue. The default value for most systems is 20. You can set it to 5 or 10. When an error occurs, listen () returns-1.
Of course, before using the system to call listen (), we need to call BIND () to bind to the required port, otherwise the system kernel will let us listen to a random port. Therefore, if you want to listen to a port, the following sequence of system calls should be used:
Socket ();
BIND ();
Listen ();

Accept ()

The system calls accept. On a remote host, you may try to connect to the host using connect ().
The port on which listen () is listening. However, this connection will wait in the queue until it is processed using accept. Call accept ()
Then, a new set of interface file descriptors will be returned to process this single connection. In this way, for the same connection
You have two file descriptors. The original file descriptor is listening to the port you specified. The new file description
It can be used to call send () and Recv ().
The call example is as follows:
# Include <sys/socket. h>
Intaccept (intsockfd, void * ADDR, int * addrlen );
The first parameter is the set interface file descriptor of the listening port. The second parameter ADDR points to the local data structure.
The pointer of sockaddr_in. The information in the call to connect () will be stored here. Through it, you can know which host is in which
Port to call you. The third parameter can also be obtained using sizeof (structsockaddr_in.
If an error occurs, accept () also returns-1. The following is a simple example:
# Include <string. h>
# Include <sys/types. h>
# Include <sys/socket. h>
# Define myport 3490
# Define backlog 10
Main ()
{
Intsockfd, new_fd;
Structsockaddr_inmy_addr;
Structsockaddr_intheir_addr;
Intsin_size;
Sockfd = socket (af_inet, sock_stream, 0 );
My_addr.sin_family = af_inet;
My_addr.sin_port = htons (myport );
My_addr.sin_addr.s_addr = inaddr_any;
Bzero (& (my_addr.sin_zero), 8 );

BIND (sockfd, (structsockaddr *) & my_addr, sizeof (structsockaddr ));
Listen (sockfd, backlog );
Sin_size = sizeof (structsockaddr_in );
New_fd = accept (sockfd, & their_addr, & sin_size );
...
Next, we can use the newly created interface file descriptor new_fd to call send () and Recv ().

Send () and Recv ()

The usage of system call send () is as follows:
Int send (INT sockfd, const void * MSG, int Len, int flags );
The first parameter is the set interface file descriptor you want to send data. It can be returned by a socket () system call or an accept () System Call.
The second parameter is the pointer to the data you want to send.
The third parameter is the length of data bytes. The fourth parameter flag is set to 0.
The following is a simple example:
Char * MSG = "beejwashere! ";
Intlen, bytes_sent;
..
Len = strlen (MSG );
Bytes_sent = Send (sockfd, MSG, Len, 0 );
...
The system calls send () to return the actual number of bytes sent, which may be less than the number of bytes you actually want to send. If the number of returned bytes is less than the number of bytes to be sent, you must send the remaining data later. -1 is returned when a send () error occurs.
The usage of System Call Recv () is similar to send:
Int Recv (INT sockfd, void * Buf, int Len, unsigned int flags );
The first parameter is the set of interface file descriptors to be read.
The second parameter is the address for saving the read information.
The third parameter is the maximum length of the buffer. The fourth parameter is set to 0.
The system calls Recv () to return the number of bytes actually read to the buffer. If an error occurs,-1 is returned.
By using the above system call, you can send and accept information through the data stream set interface.

Sendto () and recvfrom ()

Because the datagram set interface is not connected to a remote host, we must first provide the destination address before sending data packets. See:
Int sendto (INT sockfd, const void * MSG, int Len, unsigned int flags,
Conststruct sockaddr * To, inttolen );
Except for the two parameters, the other parameters are the same as when the system calls send.
The to parameter is a pointer to the sockaddr data structure containing the destination IP address and port number.
The tolen parameter can be set to sizeof (structsockaddr ).
The system calls sendto () to return the actual number of bytes sent. If an error occurs,-1 is returned.
The usage of the system call recvfrom () is similar to that of Recv:
Int recvfrom (INT sockfd, void * Buf, int Len, unsigned int flags
Struct sockaddr * From, int * fromlen );
The from parameter is a pointer to the sockaddr Data Structure on the local computer that contains the source IP address and port number.
The fromlen parameter is set to sizeof (struct sockaddr ).
The system calls recvfrom () to return the number of received bytes. If an error occurs,-1 is returned.

Close () and Shutdown ()

You can use close () to call the set interface file descriptor for closing the connection:
Close (sockfd );
In this way, no read/write operations can be performed on this interface.
You can use the system call Shutdown () to gain more control. It allows you to cut off the communication in a certain direction, or cut off the communication between the two parties:
Int Shutdown (INT sockfd, int how );
The first parameter is the set interface file descriptor that you want to disconnect communication. The second parameter how value is as follows:
0-furtherreceivesaredisall Owed
1-furthersendsaredisallowe D
2-furthersendsandreceivesa Redisallowed (likeclose ())
If Shutdown () succeeds, 0 is returned. If it fails,-1 is returned.

Getpeername ()

This system is very simple to call. It will tell you who you are at the other end of the connection:
# Include <sys/socket. h>
Int getpeername (INT sockfd, struct sockaddr * ADDR, int * addrlen );
The first parameter is the descriptor of the connected data stream set interface file.
The second parameter is the sockaddr pointer to the data structure containing the information of the other end.
The third parameter can be set to sizeof (structsockaddr ).
If an error occurs,-1 is returned for the system call.
Once you get their addresses, you can use inet_ntoa () or gethostbyaddr () to get more information.

Gethostname ()

The system calls gethostname (), which is simpler than the system calls getpeername. It returns the name of the computer where the program is running. The system calls gethostbyname () to determine the IP address of your machine.
The following is an example:
# Include <unistd. h>
Int gethostname (char * hostname, size_tsize );
If the call succeeds, gethostname returns 0. If it fails, it returns-1.

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.