C Socket Communication Programming

Source: Internet
Author: User
Tags socket error htons

Directory

1. Socket overview

2. Address and Order Processing

3. Function Introduction

4. Usage examples

1. Socket Overview 1. The TCP protocol establishes the connection through the three-time handshake protocolThe TCP protocol completes the establishment of the connection through three message segments, which is called a three-time handshake (three-way handshake), as shown in the process.

First handshake: When a connection is established, the client sends a SYN packet (SYN=J) to the server and enters the Syn_send state, waiting for the server to confirm; SYN: Synchronous sequence Number (Synchronize Sequence Numbers).

Second handshake: The server receives the SYN packet, it must confirm the customer's SYN (ACK=J+1), and also send itself a SYN packet (syn=k), that is, the Syn+ack packet, when the server enters the SYN_RECV state;
Third handshake: The client receives the server's Syn+ack packet, sends the acknowledgment packet ack (ACK=K+1) to the server, the packet is sent, the client and the server enter the established state, and the handshake is completed three times.
A full three-time handshake is also: request---answer---confirm again.

The corresponding function interface:


As you can see, when the client calls connect, the connection request is triggered, the SYN J packet is sent to the server, then connect enters the blocking state, the server hears the connection request, receives the SYN J packet, calls the Accept function to receive the request to send SYN K to the client, ACK j+ 1, then accept into the blocking state, the client receives the server SYN K, after the ACK j+1, then connect returns, and the Syn K Confirmation, the server received an ACK k+1, accept return, this three times the handshake is completed, the connection is established.

2. Programming Process

2. Address and Order Processing 1. Address structure related processing

  struct socketaddr{

unsigned short sa_family;

Char sa_data[14]

}

struct socketaddr_in{

Short int sa_family;//address family, even with what address, IPV4 or IPV6

unsigned short int sin_port;

struct IN_ADDR sin_addr;//Storage IP Address

unsigned char sin_zero[8]//padding 0 to keep also struct socketaddr same size

}

2, data storage priority order

Network address and host address translation

#include <netinet/in.h>

uint16_t htons (uint16_t host16bit)//host address to network address translation

uint32_t htols (uint32_t host32bit)

uint16_t Ntohs (uint16_t net16bit)//network address to host address translation

uint32_t Ntohl (uint32_t net32bit)

Success: Returns the byte order to convert

Error:-1

3. Address format Conversion

Converts the address of a decimal representation into a binary

#include <arpa/inet.h>

int Inet_pton (int family,//protocol type

const char *strptr,//the value to convert

void *addrptr)//converted Address

int inet_ntop (int family

void *addrptr

Char *strptr

size_t len)//size of converted Values

Success: 0

Error:-1

4. Name and address conversion

GetHostByName () Convert host name to IP address

GETHOSTBYADDR () Convert IP address to host name

#include <netbd.h>

struct hostnet *gethostbyname (const char *honstname)

Success: hostnet Type pointer

Error:-1

int getaddrinfo (const char *hostname

const CHAR *service

const struct Addrinfo *hints

struct addrinfo **result)//return result

Success: 0

Error:-1

struct Hostnet {

Char *h_name;//host Name

Char **h_aliases;

int h_addrtype;

int h_length;

Char **h_addr_list;//an array of address pointers pointing to IPV4

}

3. Function Introduction 1. Socket ()

     #include <sys/socket.h>

int socket (int family,int type,int protocal)

SUCCESS: illegal socket descriptor

Error:-1;

2. Bind ()

#include <sys/socket.h>

int bind (int sockefd,struct sockaddr *my_addr,int addrlen);

Success: 0;

Error:-1

3, Listen ()

#include <sys/socket.h>

int listen (int sockfd,int backlog)

4. Accept ()

#include <sys/socket.h>

int accept (int sockfd,struct sockaddr *addr,socklen_t *addrlen);

5. Connect ()

#include <sys/socket.h>

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

Success: 0

Error:-1

6. Send ()

int send (int sockfd,const void *msg,int len,int flags)

Success: Number of bytes Sent

Error:-1

7, recv ()

int recv (int sockfd,void *buff,int len,unsigned int flags)

Success: Number of bytes accepted

Error:-1

8, SendTo ()

int sendto (int sockfd, const void *msg,int len,unsigned int flags,struct sockaddr *to, int * tolen)

Success: Number of bytes Sent

Error:-1

9, Recvfrom ()

int recvfrom (int sockfd, const void *msg,int len,unsigned int flags,struct sockaddr *from, int * tolen)

Success: Number of bytes accepted

Error:-1

4. Simple example

  1. /* File NAME:SERVER.C */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <sys/types.h>
  7. #include <sys/socket.h>
  8. #include <netinet/in.h>
  9. #define Default_port 8000
  10. #define MAXLINE 4096
  11. int main (int argc, char** argv)
  12. {
  13. int socket_fd, CONNECT_FD;
  14. struct sockaddr_in servaddr;
  15. Char buff[4096];
  16. int n;
  17. //Initialize socket
  18. if ((SOCKET_FD = socket (af_inet, sock_stream, 0)) = = = 1) {
  19. printf ("Create socket Error:%s (errno:%d) \ n", Strerror (errno), errno);
  20. Exit (0);
  21. }
  22. //Initialize
  23. memset (&servaddr, 0, sizeof (SERVADDR));
  24. servaddr.sin_family = af_inet;
  25. SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);  The //IP address is set to Inaddr_any, allowing the system to automatically get the IP address of the machine.
  26. Servaddr.sin_port = htons (Default_port); //Set the port to Default_port
  27. //Bind the local address to the socket you created
  28. if (Bind (SOCKET_FD, (struct sockaddr*) &servaddr, sizeof (servaddr)) = =-1) {
  29. printf ("bind socket Error:%s (errno:%d) \ n", Strerror (errno), errno);
  30. Exit (0);
  31. }
  32. //Start listening for a client connection
  33. if (Listen (SOCKET_FD, ten) = =-1) {
  34. printf ("Listen socket Error:%s (errno:%d) \ n", Strerror (errno), errno);
  35. Exit (0);
  36. }
  37. printf ("======waiting for client ' s request======\n");
  38. While (1) {
  39. Blocking until there is a client connection, or more wasted CPU resources.
  40. if (connect_fd = Accept (socket_fd, (struct sockaddr*) null, null)) = =-1) {
  41. printf ("Accept socket Error:%s (errno:%d)", Strerror (errno), errno);
  42. continue;
  43. }
  44. Accept data sent by clients
  45. n = recv (connect_fd, Buff, MAXLINE, 0);
  46. Send response data to the client
  47. if (!fork ()) {/ * Forbidden City * /
  48. if (send (CONNECT_FD, "Hello,you is connected!\n", 26,0) = =-1)
  49. Perror ("Send Error");
  50. Close (CONNECT_FD);
  51. Exit (0);
  52. }
  53. Buff[n] = ' + ';
  54. printf ("recv msg from client:%s\n", buff);
  55. Close (CONNECT_FD);
  56. }
  57. Close (SOCKET_FD);
  58. }

Client:

  1. /* File NAME:CLIENT.C */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <sys/types.h>
  7. #include <sys/socket.h>
  8. #include <netinet/in.h>
  9. #define MAXLINE 4096
  10. int main (int argc, char** argv)
  11. {
  12. int sockfd, N,rec_len;
  13. Char recvline[4096], sendline[4096];
  14. Char Buf[maxline];
  15. struct sockaddr_in servaddr;
  16. if (argc! = 2) {
  17. printf ("usage:./client <ipaddress>\n");
  18. Exit (0);
  19. }
  20. if ((SOCKFD = socket (af_inet, sock_stream, 0)) < 0) {
  21. printf ("Create socket Error:%s (errno:%d) \ n", Strerror (errno), errno);
  22. Exit (0);
  23. }
  24. memset (&servaddr, 0, sizeof (SERVADDR));
  25. servaddr.sin_family = af_inet;
  26. Servaddr.sin_port = htons (8000);
  27. if (Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <= 0) {
  28. printf ("Inet_pton error for%s\n", argv[1]);
  29. Exit (0);
  30. }
  31. if (Connect (SOCKFD, (struct sockaddr*) &servaddr, sizeof (SERVADDR)) < 0) {
  32. printf ("Connect error:%s (errno:%d) \ n", Strerror (errno), errno);
  33. Exit (0);
  34. }
  35. printf ("Send msg to server: \ n");
  36. Fgets (Sendline, 4096, stdin);
  37. if (send (SOCKFD, Sendline, strlen (Sendline), 0) < 0)
  38. {
  39. printf ("Send msg Error:%s (errno:%d) \ n", Strerror (errno), errno);
  40. Exit (0);
  41. }
  42. if (Rec_len = recv (SOCKFD, buf, maxline,0) = = =-1) {
  43. Perror ("recv error");
  44. Exit (1);
  45. }
  46. Buf[rec_len] = ' + ';
  47. printf ("Received:%s", buf);
  48. Close (SOCKFD);
  49. Exit (0);
  50. }

Test:

Compiling SERVER.C

Gcc-o Server Server.c

To start a process:

./server

Show Results:

======waiting for client ' s request======

And wait for the client to connect.

Compiling client.c

Gcc-o Client Server.c

Client to connect to server:

./client 127.0.0.1

Wait for input message

Send a message, type: C + +

At this point the server side sees:

The client receives the message:

In fact, you can use Telnet to test without a client:

Telnet 127.0.0.1 8000

C Socket Communication Programming

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.