Linux Socket Programming Example (simplest TCP and UDP two examples)

Source: Internet
Author: User
Tags network function htons

First, socket programming

Network function is an important feature of Uinux/linux, has a long history, so there is a very fixed programming routines.

TCP-based network programming:

Based on the connection, the server and client remain connected and cannot be disconnected during the interactive process. Re-send all error data, data validation, to ensure the correctness, completeness and sequence of data,

The disadvantage is that the resources consumed are relatively large.

UDP-based network programming:

No connection protocol, in the network interaction process does not maintain the connection, only need to connect when sending data, do not resend, verify the data. The advantage is that the resource consumption is low, the data reliability integrity

There is no guarantee of order.

Second, the programming steps:

Server:

① creating socket Sockets ()

② Prepare correspondence Address

③ will create the socket and communication address binding bind ()

④ Listening Port Listen ()

⑤ Waiting for Client Connection Accpet ()

⑥ communication both send and receive data read ()/write ()

Send ()/recv ()

⑦ Closing the socket

Client:

① creating socket Sockets ()

② Prepare correspondence Address

③ Connect to server Connect ()

④ send and receive data read ()/write ()

Send ()/recv ()

⑤ Closing the socket

Third, the API detailed

①socket () function

int socket (domain, type, protocol)

Domain

Af_unix/af_local/af_file: Local Communication

Af_inet: Network communication IPv4

AF_INET6: Network communication ipv6

Note: If AF is converted to PF effect

Type, select the type of communication, mainly including:

Sock_stream:tcp

Sock_dgram:udp

Protocol, originally should specify the communication protocol, but now basically obsolete, because the protocol has been specified in the first two parameters to complete, to 0 can

②bind () function

int bind (int sockfd, struct sockaddr *addr, size)

SOCKFD: Socket descriptor to bind

Size: The amount of memory space occupied by the second parameter

Addr: Involving three data structures struct sockaddr, Sockaddr_un, sockaddr_in

SOCKADDR, used primarily for function parameters, is not responsible for storing data

Sockaddr_un, address used for local communication in the presence of local communications (SYS/UN.H)

SOCKADDR_IN, the address data that is responsible for storing network traffic in the presence of network communication

struct SOCKADDR_IN {

sin_family; Used to specify the protocol family, and the parameters of the socket () remain consistent

Sin_port; Port number used by network communication

SIN_ADDR; IP address for storage network traffic

}

③htons

④inet_aton

⑤listen () function

int listen (int sockfd, int backlog)

SOCKFD: The socket identified by the SOCKFD parameter is in passive mode so that it can accept the connection request

Backlog: Indicates the maximum length of the pending connection request queue, that is, the maximum number of pending connection requests that are allowed to exist. If the server's pending connection request has reached this value, the client's operation to connect to the server via connect () will return-1 with error econnrefused

⑥accpet () function

int Accpet (SOCKFD, struct sockaddr* addr, socklen_t *addrlen)

A connection request that is taken out of the pending connection request queue from the socket identified by the SOCKFD parameter, creating a new socket for that connection communication, and returning the descriptor of the socket

Addr and Addrlen to output the address information of the initiator of the connection request

Return value: Failed to create socket descriptor for new communication with client-1, error

⑦inet_ntoa

⑧RECV () function

int recv (int sockfd, buf, Len, Flags)

Flags, usually taking 0: blocking the collection of data

O_nonblock: does not block, returns an error message if no data is received

return value:

>0, actual bytes of data accepted

-1, errors, error

0, the other end of the communication is off

⑨send () function

int send (int sockfd, buf, Len, Flags)

Flags: usually take 0, block send

O_nonblock: does not block, returns an error message if no data is received

⑩connect () function

int connect (int sockfd, addr, Addr_len)

Parameter reference bind ()

Iv. Examples of TCP


Copy Code
1/*******************************
2 client.c
3 ********************************/
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <sys/types.h>
9 #include <sys/socket.h>
Ten #include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
13
int main ()
15 {
16/*1 Create socket*/
SOCKFD int = socket (af_inet, sock_stream, 0);
if (SOCKFD = =-1)
19 {
Perror ("Socket failed");
Exit (-1);
22}
23/*2 Prepare Correspondence address */
Sockaddr_in addr, a struct;
addr.sin_family = af_inet;
26/* Set the port number for the server process */
Addr.sin_port = htons (port);
28/* Server Host IP address */
Inet_aton ("192.168.182.10", &addr.sin_addr);
30
31/*3 Connection Server */
int res = connect (SOCKFD,
(struct sockaddr *) &addr,
sizeof (addr));
if (res = =-1)
36 {
PNS perror ("Connect failed");
-Exit (-1);
39}
+ printf ("Connection server succeeded ... \ n");
41/*4 and Server Exchange data */
BUF[100] = {0};
*str char = "Can I borrow some money ...";
$ write (SOCKFD, str, strlen (str));
Read (SOCKFD, buf, sizeof (BUF));
* printf ("server says:%s\n", buf);
47
48/* Close Connection */
(SOCKFD);
return 0;
51}
Copy Code

Copy Code
1/************************************
2 SERVER.C
3 *************************************/
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <sys/types.h>
Ten #include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
14
int main ()
16 {
17/*1 Create socket*/
SOCKFD int = socket (af_inet, sock_stream, 0);
if (SOCKFD = =-1)
20 {
Perror ("Socket failed");
Exit (-1);
23}
24/*2 Prepare correspondence address */
the struct sockaddr_in addr;
addr.sin_family = af_inet;
Addr.sin_port = htons (port);
Inet_aton ("192.168.182.10", &addr.sin_addr);
29
30/*3 bind socket and communication address */
int res = bind (SOCKFD, struct sockaddr *) &addr,
sizeof (addr));
if (res = =-1)
34 {
Perror ("Bind failed");
+ Exit (-1);
37}
38/*4 Listening Port */
Listen res = (SOCKFD, 100);
if (res = =-1)
41 {
Perror ("Listen Failed");
Exit (-1);
44}
printf ("Start listening on%d ports, waiting for client connections ... \ n",
(PORT);
47/*5 Processing the connection request from the receiving client */
48//For saving client address information
Sockaddr_in fromaddr of the struct;
What effect does 0/*len take? */
Wuyi socklen_t len = sizeof (FROMADDR);
CLIENTFD int = Accept (SOCKFD,
(struct sockaddr *) &fromaddr,
&len);
if (clientfd = =-1)
56 {
Perror ("Accept failed");
(-1);
59}
printf ("There is a client connected to the server, it is:%s\n",
Inet_ntoa (FROMADDR.SIN_ADDR));
62/*6 Processing Client Data */
buf[100 char] = {0};
int count = recv (clientfd, buf, sizeof (BUF), 0);
printf ("read from client to%d bytes:%s\n",
(buf count,);
*str char = "Welcome to your client";
(CLIENTFD, str, strlen (str), 0);
69/* Close connection */
Close (CLIENTFD);
Close (SOCKFD);
return 0;
73}
Copy Code
V. Examples of UDP


Copy Code
1/********************************
2 udp_client.c
3 *********************************/
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <sys/types.h>
9 #include <sys/socket.h>
Ten #include <netinet/in.h>
#include <arpa/inet.h>
12
#define PORT 12345
int main ()
15 {
16/*1 Create socket*/
+ int sd = socket (pf_inet, SOCK_DGRAM, 0);
if (SD = =-1)
19 {
Perror ("Socket failed");
Exit (-1);
22}
23/*2 Preparation Address */
Sockaddr_in addr, a struct;
addr.sin_family = pf_inet;
Addr.sin_port = htons (port);
Inet_aton ("192.168.182.10", &addr.sin_addr);
28/*3 for Communication */
Char *str = "Can I borrow some money?";
SendTo (SD, STR, strlen (str), 0,
(struct sockaddr *) &addr,
sizeof (addr));
(buf[100 char) = {0};
the int len = sizeof (addr);
Recvfrom (SD, buf, sizeof (BUF), 0,
(struct sockaddr *) &addr,
Panax Notoginseng &len);
%s\n printf ("server says:", buf);
Close (SD);
40}
Copy Code

Copy Code
1/********************************
2 UDP_SERVER.C
3 *********************************/
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <sys/types.h>
9 #include <sys/socket.h>
Ten #include <netinet/in.h>
#include <arpa/inet.h>
12
#define PORT 12345
int main ()
15 {
16/*1 Create socket*/
+ int sd = socket (pf_inet, SOCK_DGRAM, 0);
if (SD = =-1)
19 {
Perror ("Socket failed");
Exit (-1);
22}
23/*2 Preparation Address */
Sockaddr_in addr, a struct;
addr.sin_family = pf_inet;
Addr.sin_port = htons (port);
Inet_aton ("192.168.182.10", &addr.sin_addr);
/*3 Socket Addr Binding */
int res = bind (SD, (struct sockaddr *) &addr,
sizeof (addr));
if (res = =-1)
32 {
Perror ("Bind failed");
Exit (-1);
35}
36/*4 for Communication */
Panax Notoginseng while (1)
38 {
(buf[100 char) = {0};
Sockaddr_in fromaddr;
the int len = sizeof (FROMADDR);
Recvfrom (SD, buf, sizeof (BUF), 0,
(struct sockaddr *) &fromaddr,
&len);
printf ("Data received from client%s:%s\n",
Inet_ntoa (FROMADDR.SIN_ADDR),
(BUF);
*str char = "No problem, how much to borrow";
SendTo (SD, STR, strlen (str), 0,
(struct sockaddr *) &fromaddr,
sizeof (FROMADDR));
52}
Close (SD);
54
55}

Http://www.cnblogs.com/jiangson/p/5977601.html

Linux Socket Programming Example (simplest TCP and UDP two examples)

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.