Introduction to several necessary network functions for Linux Network Programming

Source: Internet
Author: User
Tags localhost 8888 socket error
Introduction to several necessary network functions for Linux Network Programming-general Linux technology-Linux programming and kernel information. The following is a detailed description. In Linux, network programming is implemented through socket. network programs call socket and several other functions to return a communication file descriptor. we can regard this descriptor as a common file descriptor for operation, this is the benefit of linux's device independence. we can exchange data between networks by reading and writing the descriptor.

1 socket
Int socket (int domain, int type, int protocol)

Domain: indicates the communication clan (AF_UNIX and AF_INET) used by the host where the network program is located ). AF_UNIX can only be used for communication between processes in a single Unix system, while AF_INET is for Internet, therefore, communication can be allowed between remote hosts (when we find that the domain option is PF _ * rather than AF _ * When we use man socket, because glibc is a posix implementation, we use PF instead of AF, but we can all use it ).

Type: the communication protocol used by our network program (SOCK_STREAM, SOCK_DGRAM, etc.) SOCK_STREAM indicates that we use the TCP protocol, which provides sequential, reliable, and bidirectional, connection-oriented bit stream. SOCK_DGRAM indicates that we use UDP protocol, which only provides fixed-length, unreliable, and connectionless communication.

Protocol: because we have specified the type, we generally only need to use 0 to replace it with socket to make basic preparations for network communication. if the call succeeds, the file descriptor is returned. If the call fails, the value-1 is returned. You can see the error details in errno.


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

Sockfd: The file descriptor returned by a socket call.

Addrlen: the length of the sockaddr structure.

My_addr: a pointer to sockaddr. sockaddr is defined in it.

Struct sockaddr {
Unisgned short as_family;
Char sa_data [14];
};

However, due to system compatibility, we generally do not need this header file, instead of using another structure (struct sockaddr_in). sockaddr_in is defined in it.
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 the Internet, so sin_family is generally AF_INET, and sin_addr is set to INADDR_ANY, which indicates that it can communicate with any host, and sin_port is the port number we want to listen. sin_zero [8] is used for filling. bind binds the local port with the file descriptor returned by the socket. 0 is returned for success. The failure is the same as that of socket.

3 listen
Int listen (int sockfd, int backlog)

Sockfd: The file descriptor after bind.

Backlog: set the maximum length of the Request queue. when multiple client programs are connected to the server, use this to indicate the length of the queue. the listen function changes the file descriptor of bind to the listening socket. the returned result is the same as that of bind.

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

Sockfd: The file descriptor after listen.

Addr and addrlen are used to fill in the client program. The server only needs to pass the pointer. bind, listen, and accept are functions used by the server. When an accept is called, the server program will be blocked until a client program sends a connection. when accept succeeds, the final server file descriptor is returned. At this time, the server can write information to this descriptor. -1 is returned when a failure occurs.


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

Sockfd: file descriptor returned by the socket.

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

Addrlen: length of serv_addr

The connect function is used by the client to connect to the server. 0 is returned when the connection is successful, and-1 is returned when the file descriptor for communication with the server fails.


6 instances

Server programs


/******* Server program (server. c )************/
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include

Int main (int argc, char * argv [])
{
Int sockfd, new_fd;
Struct sockaddr_in server_addr;
Struct sockaddr_in client_addr;
Int sin_size, portnumber;
Char hello [] = "" Hello! Are You Fine? "";

If (argc! = 2)
{
Fprintf (stderr, "" Usage: % s portnumbera "", argv [0]);
Exit (1 );
}

If (portnumber = atoi (argv [1]) <0)
{
Fprintf (stderr, "" Usage: % s portnumbera "", argv [0]);
Exit (1 );
}

/* The server starts to establish the socket descriptor */
If (sockfd = socket (AF_INET, SOCK_STREAM, 0) =-1)
{
Fprintf (stderr, "" Socket error: % s a "", strerror (errno ));
Exit (1 );
}

/* Fill in the sockaddr structure on the server */
Bzero (& server_addr, sizeof (struct sockaddr_in ));
Server_addr.sin_family = AF_INET;
Server_addr.sin_addr.s_addr = htonl (INADDR_ANY );
Server_addr.sin_port = htons (portnumber );

/* Bind the sockfd descriptor */
If (bind (sockfd, (struct sockaddr *) (& server_addr), sizeof (struct sockaddr) =-1)
{
Fprintf (stderr, "" Bind error: % s a "", strerror (errno ));
Exit (1 );
}

/* Listen to the sockfd descriptor */
If (listen (sockfd, 5) =-1)
{
Fprintf (stderr, "" Listen error: % s a "", strerror (errno ));
Exit (1 );
}

While (1)
{
/* Server blocking until the Client Program establishes a connection */
Sin_size = sizeof (struct sockaddr_in );
If (new_fd = accept (sockfd, (struct sockaddr *) (& client_addr), & sin_size) =-1)
{
Fprintf (stderr, "" Accept error: % s a "", strerror (errno ));
Exit (1 );
}

Fprintf (stderr, "" Server get connection from % s "",
Inet_ntoa (client_addr.sin_addr ));
If (write (new_fd, hello, strlen (hello) =-1)
{
Fprintf (stderr, "" Write Error: % s "", strerror (errno ));
Exit (1 );
}
/* The communication has ended */
Close (new_fd );
/* Loop next */
}
Close (sockfd );
Exit (0 );
}


Client Program

/******* Client program client. c ************/
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include

Int main (int argc, char * argv [])
{
Int sockfd;
Char buffer [1024];
Struct sockaddr_in server_addr;
Struct hostent * host;
Int portnumber, nbytes;

If (argc! = 3)
{
Fprintf (stderr, "" Usage: % s hostname portnumbera "", argv [0]);
Exit (1 );
}

If (host = gethostbyname (argv [1]) = NULL)
{
Fprintf (stderr, "" Gethostname error "");
Exit (1 );
}

If (portnumber = atoi (argv [2]) <0)
{
Fprintf (stderr, "" Usage: % s hostname portnumbera "", argv [0]);
Exit (1 );
}

/* The customer program starts to establish the sockfd descriptor */
If (sockfd = socket (AF_INET, SOCK_STREAM, 0) =-1)
{
Fprintf (stderr, "" Socket Error: % sa "", strerror (errno ));
Exit (1 );
}

/* Fill in the information of the client program on the server */
Bzero (& server_addr, sizeof (server_addr ));
Server_addr.sin_family = AF_INET;
Server_addr.sin_port = htons (portnumber );
Server_addr.sin_addr = * (struct in_addr *) host-> h_addr );

/* The client program initiates a connection request */
If (connect (sockfd, (struct sockaddr *) (& server_addr), sizeof (struct sockaddr) =-1)
{
Fprintf (stderr, "" Connect Error: % sa "", strerror (errno ));
Exit (1 );
}

/* Connection successful */
If (nbytes = read (sockfd, buffer, 1024) =-1)
{
Fprintf (stderr, "" Read Error: % s "", strerror (errno ));
Exit (1 );
}
Buffer [nbytes] = '''';
Printf ("" I have received: % s "", buffer );
/* End communication */
Close (sockfd );
Exit (0 );
}


MakeFile
Here we use the GNU make utility to compile. For more information about make, see Make.

######### Makefile ###########
All: server client
Server: server. c
Gcc $ ^-o $ @
Client: client. c
Gcc $ ^-o $ @

After running make, two programs, server and client, are generated to run first. /server portnumber & (set portnumber to a number greater than 1204 that does not appear in/etc/services. Set portnumber to 8888.) then run. /client localhost 8888. (You can also use telnet and netstat for a try .) the above is the simplest network program, but it is also annoying. there are many functions that we have not explained yet. I will give a detailed description in the next chapter.


7. Conclusion
In general, network programs are composed of two parts: the client and the server. The steps for establishing network programs are generally:

Server
Socket --> bind --> listen --> accept

Client
Socket --> connect
Related Article

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.