Summary of Linux socket common functions

Time:2019-11-23

======== TCP ========
TCP_Server
socket()
bind()
listen()
accept()
write()
read()
Close() and shutdown()

TCP_Client
socket()
connect()
Send() and recv()
Close() and shutdown()

======== UDP ========
UDP_Server
socket()
bind()
Sendto() and recvfrom()
Close() and shutdown()

UDP_Client
socket()
Sendto() and recvfrom()
Close() and shutdown()

getpeername()
gethostname()

——————————————————————————–
socket()
We use the system call socket () to get the file descriptor:
#include<sys/types.h>
#include<sys/socket.h>
int socket(int domain, int type, int protocol);
The first parameter, domain, is set to AF? INET.
The second parameter is the type of socket: sock “stream or
Sock? Dgram. The third parameter is set to 0.
The system call socket() only returns a socket interface descriptor. If there is an error, it returns – 1.
——————————————————————————–

bind()
Once you have a socket, the next step is to bind the socket to a port on the local computer. But it’s not necessary if you just want to use connect().
Here is how to use the system call 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 data structure SOCKADDR. The data structure SOCKADDR includes information about your address, port and IP address.
The third parameter, addrlen, can be set to sizeof (structsockaddr).
Here is an example:

#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#define MYPORT 3490
main()
{
	int sockfd;
	struct sockaddr_in my_addr;
	sockfd=socket(AF_INET,SOCK_STREAM,0); /*do someerror checking!*/
	my_addr.sin_family=AF_INET;           /*hostbyteorder*/
	my_addr.sin_port=htons(MYPORT);       /*short,network byte order*/
	my_addr.sin_addr.s_addr=inet_addr("132.241.5.10");
	bzero(&(my_addr.sin_zero),8);         /*zero the rest of the struct*/
    /*don't forget your error checking for bind():*/
	bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr));
...
}

If there is an error, bind() also returns – 1.
If you use the connect () system call, you don’t have to know the port number you are using. When you call connect(), it checks whether the socket interface is bound, and if not, it will allocate an idle port.
——————————————————————————–

connect()
The usage of the 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 also a set of interface file descriptors, which is returned by the system call socket().
The second parameter is serv? Addr, which is a pointer to the data structure SOCKADDR, including the destination port and IP address.
The third parameter can be obtained by using sizeof (structsockaddr).
Here 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()
{
	int sockfd;
	struct sockaddr_in dest_addr;            /*will hold the destination addr*/
	sockfd=socket(AF_INET, SOCK_STREAM, 0);  /*do some error checking!*/
    dest_addr.sin_family=AF_INET;            /*hostbyteorder*/
	dest_addr.sin_port=htons(DEST_PORT);     /*short,network byte order*/
	dest_addr.sin_addr.s_addr=inet_addr(DEST_IP);
	bzero(&(dest_addr.sin_zero), 8);          /*zero the rest of the struct*/
	/*don'tforgettoerrorchecktheconnect()!*/
	connect(sockfd,(struct sockaddr *)&dest_addr, sizeof(struct sockaddr));
	...
}

Similarly, if there is an error, connect() will return – 1.
——————————————————————————–

listen()
If you want to not connect to a remote host, that is, you want to wait for an incoming connection request before processing them. This way, you do it by calling listen () first, then accept ().
The form of system call listen() is as follows:
intl isten(int sockfd, int backlog);
The first parameter is the set interface file descriptor returned by the system call socket().
The second parameter is the number of connections allowed to enter the queue. Incoming connection requests are queued before they are answered with the system call accept(). This value is the maximum number of requests that can be owned in the queue. The default setting for most systems is 20. You can set it to 5 or 10. When there is an error, listen() will return a value of – 1.
Of course, before using the system 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. So, if you want to listen to a port, here is the sequence of system calls you should use:
socket();
bind();
listen();
/*accept()goeshere*/
——————————————————————————–

accept()
The system call accept() is a bit more complex. The remote host may try to use connect() to connect you to the
The port that listen() is listening on. But the connection will wait in the queue until it is processed using accept(). Call accept()
After that, a new set of interface file descriptors will be returned to handle this single connection. So, for the same connection
In other words, you have two file descriptors. The original file descriptor is listening to the port you specified. The new file descriptor
The descriptor can be used to call send() and recv().
An example of the call is as follows:
#include<sys/socket.h>
intaccept(int sockfd, void *addr, int *addrlen);
The first parameter is the socket interface file descriptor that is listening on the port. The second parameter, addr, points to the local data structure
Pointer to SOCKADDR? In. The information in the call to connect () is 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 there is an error, accept() will also return – 1. Here is a simple example:

#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#define MYPORT 3490  /*theportuserswillbeconnectingto*/
#define BACKLOG 10   /*howmanypendingconnectionsqueuewillhold*/
main()
{
	int sockfd, new_fd;              /*listenonsock_fd,newconnectiononnew_fd*/
	struct sockaddr_in my_addr;      /*myaddressinformation*/
	struct sockaddr_in their_addr;   /*connector'saddressinformation*/
	int sin_size;
	sockfd=socket(AF_INET, SOCK_STREAM, 0);  /*dosomeerrorchecking!*/
	my_addr.sin_family=AF_INET;              /*hostbyteorder*/
	my_addr.sin_port=htons(MYPORT);          /*short,networkbyteorder*/
	my_addr.sin_addr.s_addr=INADDR_ANY;      /*auto-fillwithmyIP*/
	bzero(&(my_addr.sin_zero),8);            /*zerotherestofthestruct*/
	/*don'tforgetyourerrorcheckingforthesecalls:*/
	bind(sockfd,(struct sockaddr *)&my_addr, sizeof(struct sockaddr));
	listen(sockfd,BACKLOG);
	sin_size=sizeof(struct sockaddr_in);
	new_fd=accept(sockfd,&their_addr,&sin_size);
	...
}

Next, we will be able to call send() and recv() using the newly created set of interface file descriptors, new FD.
——————————————————————————–

Send() and recv()
The usage of the system call send() is as follows:
int send(int sockfd, const void* msg, int len, int flags);
The first parameter is the set of interface file descriptors you want to send data to. It can be returned by socket () system call or by accept () system call.
The second parameter is a pointer to the data you want to send.
The third parameter is the byte length of the data. The fourth parameter flag is set to 0.
Here is a simple example:
char*msg=”Beejwashere!”;
intlen,bytes_sent;
..
len=strlen(msg);
bytes_sent=send(sockfd, msg, len, 0);

The system call send() returns the actual number of bytes sent, which may be less than the number of bytes you actually want to send. If the number of bytes returned is less than the number of bytes to be sent, you must send the remaining data later. When send() fails, – 1 is returned.
The 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 read.
The second parameter is the address where the read-in information is stored.
The third parameter is the maximum length of the buffer. The fourth parameter is set to 0.
The system call recv() returns the number of bytes actually read into the buffer and – 1 if there is an error.
Using the above system call, you can send and receive information through the data flow socket interface.
——————————————————————————–

Sendto() and recvfrom()
Because the datagram socket interface is not connected to the remote host, we must first give the destination address before sending the data packet
int sendto(int sockfd, const void* msg, int len, unsigned int flags,
conststruct sockaddr*to, inttolen);
With the exception of two parameters, the other parameters are the same as when the system calls send().
The parameter to is a pointer to the data structure SOCKADDR containing the destination IP address and port number.
The parameter tolen can be set to sizeof (structsockaddr).
The system call sendto() returns the number of bytes actually sent, or – 1 if there is an error.
The use method of system call recvfrom() is also very similar to that of recv():
int recvfrom(int sockfd, void* buf, int len, unsigned int flags
struct sockaddr* from, int* fromlen);
The parameter from is a pointer to the data structure SOCKADDR containing the source IP address and port number in the local computer.
The parameter fromlen is set to sizeof (struct SOCKADDR).
The system call recvfrom() returns the number of bytes received and – 1 if there is an error.
——————————————————————————–

Close() and shutdown()
You can use the close() call to close the connection’s socket file descriptor:
close(sockfd);
In this way, you can no longer read or write to this set of interfaces.
Use the system call shutdown() to have more control. It allows you to cut off communication in one direction, or both:
int shutdown(int sockfd, int how);
The first parameter is the set of interface file descriptors that you want to cut off communication. The second parameter how is as follows:
0—Furtherreceivesaredisallowed
1—Furthersendsaredisallowed
2—Furthersendsandreceivesaredisallowed(likeclose())
Shutdown() returns 0 if it succeeds and – 1 if it fails.
——————————————————————————–

getpeername()
The call to this system is very simple. It will tell you who is 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 connected data stream socket interface file descriptor.
The second parameter is a pointer to the data structure SOCKADDR that contains the information on the other end.
The third parameter can be set to sizeof (struct SOCKADDR).
If an error occurs, the system call returns – 1.
Once you get their addresses, you can use inet_ntoa() or gethostbyaddr() to get more information.
——————————————————————————–

gethostname()
The system call gethostname() is simpler than the system call getpeername(). It returns the name of the computer on which the program is running. The system call gethostbyname () can use this name to determine the IP address of your machine.
Here is an example:
#include<unistd.h>
int gethostname(char*hostname, size_t size);
If successful, gethostname will return 0. If it fails, it returns – 1.

Recommended Today

Server Core Knowledge

Catalog 1. Computer: a tool to assist human brain 2. Composition of computer hardware 3. power supply 4.CPU 5. memory 6. Classification of computer use 7. Introduction to common Internet servers 8. Server classification 1. Computer: a tool to assist human brain Nowadays people touch computers almost all the time! Whether it’s a desktop computer, […]