Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction of linux Network programming socket

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "the introduction of linux network programming socket". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the introduction of linux network programming socket".

one。 Concept introduction

Network programs are divided into server programs and client programs. The server is the party that provides the service, and the client is the party that requests the service. But the reality is that the client-side and server-side roles of some programs are not so obvious, that is, they are client-side and server-side.

When we write network programs, we generally communicate on the basis of TCP protocol or UDP protocol.

TCP: (Transfer Control Protocol) Transmission Control Protocol is a connection-oriented protocol. When our network programs use this protocol, the network can ensure that the transmission between our client and server is reliable.

UDP: (User Datagram Protocol) the user Datagram protocol is a non-connection-oriented protocol that does not guarantee the reliability of the connection of our network programs.

Which kind of protocol is used in our network program depends on the specific situation. For example, if it is a large amount of data communication, and the data integrity requirements are not particularly high, then the UDP protocol can be used to get a faster transmission rate. If we want to achieve some functions such as file transfer and social communication, we need to use TCP protocol to communicate to ensure the reliability of transmission.

two。 Introduction to Elementary Network function

Nt socket (int domain, int type,int protocol)

Domain: explain the communication protocol family (AF_UNIX and AF_INET, etc.) used by the host where our network program is located.

AF_UNIX can only be used for interprocess communication in a single Unix system.

AF_INET is for Internet, so it can be used remotely.

Communication between hosts (when we man socket, we find that the domain option is PF_* rather than AF_*, because glibc is the implementation of posix, so we use PF instead of AF.

But we can all use it.

Type: the communication protocol used by our network programs (SOCK_STREAM,SOCK_DGRAM, etc.)

SOCK_STREAM indicates that we are using the TCP protocol, which provides a sequential, reliable, bi-directional, connection-oriented bit stream.

SOCK_DGRAM indicates that we are using the UDP protocol, which only provides fixed-length, unreliable, connectionless communications.

Protocol: since we specify type, we usually only need to use 0 instead of socket to make basic preparations for network communication.

Return file descriptor on success and-1 on failure. Look at errno to know the details of the error.

Int bind (int sockfd, struct sockaddr * my_addr, int addrlen)

Sockfd: is the file descriptor returned by the socket call.

Addrlen: the length of the sockaddr structure.

My_addr: is a pointer to sockaddr. Have the definition of sockaddr in

Struct sockaddr {

Unisgned short as_family

Char sa_data [14]

}

However, due to system compatibility, we generally do not use this header file, but use another structure (struct sockaddr_in) instead. Have the definition of sockaddr_in in

Struct sockaddr_in {

Unsigned short sin_family

Unsigned short int sin_port

Struct in_addr sin_addr

Unsigned char sin_zero [8]

}

We mainly use Internet, so

Sin_family is usually AF_INET.

Setting sin_addr to INADDR_ANY means you can communicate with any host.

Sin_port is the port number we want to listen on. Sin _ zero [8] is used to populate.

Bind bundles the local port with the file descriptor returned by socket. Success returns 0, and failure is the same as socket.

Int listen (int sockfd,int backlog)

Sockfd: is the file descriptor after bind.

Backlog: sets the maximum length of the request queue. Use this to indicate the queue length that can be described when multiple client programs are connected to the server.

The listen function changes the file descriptor of bind into a listening socket. The situation returned is the same as bind.

Int accept (int sockfd, struct sockaddr * addr,int * addrlen)

Sockfd: is the file descriptor after listen.

Addr,addrlen is used to fill in the client program, and the server only needs to pass the pointer. Bind,listen and accept are server-side functions

When accept is called, the server-side program blocks until a client program issues a connection. If accept succeeds, return the last server-side file descriptor

At this point, the server can write information to the descriptor. Returns-1 on failure

Int connect (int sockfd, struct sockaddr * serv_addr,int addrlen)

The file descriptor returned by sockfd:socket.

Serv_addr: stores the connection information on the server side. Where sin_add is the address of the server

Length of addrlen:serv_addr

The connect function is used by the client to connect with the server. Returns-1. 0 if the file descriptor that communicates with the server fails.

For more functions, please see man. .

Int getaddrinfo (const char * node, const char * service

Const struct addrinfo * hints

Struct addrinfo * * res)

three。 Examples of the use of elementary network functions

A textbook server-side program flow is:

Create socket socket ()-- > bind socket to ip address bind ()-> build listening socket listen ()-> start waiting for client request accpet ()

The detailed code is as follows:

The code is as follows:

# include

# include

# include

# include

# include

# include

# include

# include

# include

Int main (int argc, char * argv [])

{

Int sockfd,connfd

Struct sockaddr_in srvaddr

Struct sockaddr_in cliaddr

Int len,port

Char hello [] = "Hi,welcome to linux-code!\ n"

If ((sockfd=socket (AF_INET,SOCK_STREAM,0) =-1) {

Fprintf (stderr, "Socket error:%s\ n\ a", strerror (errno))

Exit (1)

}

/ * the server side is populated with sockaddr structure * /

Bzero (& srvaddr,sizeof (struct sockaddr_in))

Srvaddr.sin_family=AF_INET

Srvaddr.sin_addr.s_addr=htonl (INADDR_ANY)

Srvaddr.sin_port=htons (1113)

/ * bind sockfd descriptor * /

If (bind (sockfd, (struct sockaddr *) (& srvaddr), sizeof (struct sockaddr)) =-1) {

Fprintf (stderr, "Bind error:%s\ n\ a", strerror (errno))

Exit (1)

}

/ * listen for sockfd descriptor * /

If (listen (sockfd,5) =-1) {

Fprintf (stderr, "Listen error:%s\ n\ a", strerror (errno))

Exit (1)

}

Len=sizeof (struct sockaddr_in)

While (1) {/ * the server blocks until the client establishes a connection * /

If ((connfd=accept (sockfd, (struct sockaddr *) (& cliaddr), & len)) =-1) {

Fprintf (stderr, "Accept error:%s\ n\ a", strerror (errno))

Exit (1)

}

Fprintf (stderr, "Server get connection from% s\ n", inet_ntoa (cliaddr.sin_addr))

If (write (connfd,hello,strlen (hello)) =-1) {

Fprintf (stderr, "Write Error:%s\ n", strerror (errno))

Exit (1)

}

/ * this communication is over * /

Close (connfd)

/ * cycle next * /

}

Close (sockfd)

Exit (0)

}

A textbook client program flow is:

Establish a socket socket ()-> establish a connection with the server connect ()

The detailed code is as follows:

The code is as follows:

# include

# include

# include

# include

# include

# include

# include

# include

# include

Int main (int argc, char * argv []) {

Int sockfd; char buf [1024]

Struct sockaddr_in srvaddr

Struct hostent * phost; int nbytes

If (Argcroup 3) {

Fprintf (stderr, "Usage:%s\ a\ n", argv [0])

Exit (1)

}

/ * the client starts to create sockfd descriptors * /

If ((sockfd=socket (AF_INET,SOCK_STREAM,0) =-1) {

Fprintf (stderr, "socket Error:%s\ a\ n", strerror (errno))

Exit (1)

}

/ * the client program fills in the data of the server * /

Bzero (& srvaddr,sizeof (srvaddr))

Srvaddr.sin_family=AF_INET

Srvaddr.sin_port=htons (atoi (argv [2]))

If (inet_pton (AF_INET, argv [1], & srvaddr.sin_addr)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report