Network Programming Learning NOTE: Socket programming under Linux

Source: Internet
Author: User
Tags socket error unix domain socket server port htons

A socket is a way of communicating with the process by invoking some APIs to enable interprocess communication, establishing a connection, and sending and receiving information as shown in the following procedure:

The use of these functions is as follows:

1, int socket (int protocolfamily, int type, int protocol); Return descriptor SOCKFD

    • L protocolfamily: Protocol family, Af_inet (IPV4), Af_inet6 (IPV6), af_local (or Af_unix,unix domain socket), af_route, etc. The protocol family determines the socket address type, must use the corresponding address in the communication, such as Af_inet decided to use IPV4 address (32 bit) and port number (16 bit), Af_unix decided to use an absolute path name as the address
    • L Type: Specifies the socket type. Commonly used types are, Sock_stream, Sock_dgram, Sock_raw, Sock_packet, Sock_seqpacket, etc.
    • L Protocol: Protocol Name

After the invocation of the socket is created, the returned descriptor exists in the protocol family space, but there is no specific address that must be done by bind

2, int bind (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);

    • L Sockfd:socket Description Word, Socket return value
    • L Addr: A const struct *ADDR pointer that points to the protocol address of the SOCKFD to bind. This address structure differs depending on the address protocol family when the socket is created

For example, IPV4:

struct sockaddr_in {sa_family_t    /**/in_port_t      sin_port;    /*  */struct in_addr sin_addr;   /* */}; struct in_addr{  //  address in network byte order};
    • L Addrlen: The length of the corresponding address

3, int listen (int sockfd, int backlog); Server listener function

    • L Sockfd:socket Description Word, Socket return value
    • L BACKLOG:SOCKET The maximum number of connections that can be queued

The Listen function changes the socket to a passive type, waiting for a client connection request

4, int connect (int sockfd, const struct *ADDR, socklen_t addrlen);

    • L Sockfd:socket Description Word, Socket return value
    • L Addr: The server's socket address
    • L Addrlen:socket Length of address

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

    • L Sockfd:socket Description Word, Socket return value
    • L Addr: A result parameter that receives a return value pointing to the address of the client and can be set to NULL if the customer's address is not a concern
    • L Addrlen: The result parameter, receives the above addr structure size, indicates the addr structure occupies the number of bytes, also can be null

Accept () successfully returns a socket descriptor that represents the descriptor of the received socket. Otherwise the return value is Invalid_socket.

6, ssize_t Send (int sockfd, const void *buf, ssize_t len, int flags);

    • L Sockfd:socket Description Word, Socket return value
    • L BUF: Data to be sent in buffer
    • L Len: The size of the data to be transferred
    • L Flag: The general value is 0, which affects the optional part of the TCP header

Send copy its own data to the kernel's send buffer, the return value is [ -1,size]:

      • Return-1 description failed to send data, system internal problem
      • return [0,size]: Since send is writing data from the kernel's send buffer, the remaining length in send buffer is M, return min (m, size), return 0 is no space for send buffer

7, ssize_t recv (int sockfd, void *buf, ssize_t len, int flags);

The meaning of each parameter is basically the same as send, and the recv operation copies the data in the kernel to the inside of the application

The return value is [ -1,size]:

      • Return-1 indicates a receive failure, socket failure, recv operation due to internal cause interruption, etc.
      • Return 0 indicates no data, receive send in TCP has a timeout, when timeout has no data returned 0
      • Returns the [1,SIZE]:RECV operation when copying data from the kernel, how many copies of the data, the kernel now receives data of length m, returns min (m, size);

8, int close (int fd);

An echo small example, the client sends to the server what the server will return to the client what information:

1. Server code:

#include <stdio.h>#include<stdlib.h>#include<string.h>#include<errno.h>#include<sys/types.h>//Basic System data type, the header file of the system's basic system data type#include <sys/socket.h>#include<netinet/inch.h>//Internet address Family#include <arpa/inet.h>//IP Address conversion function Inet_pton#include <unistd.h>//Close#include<iostream>intMainintargcChar**argv) {    intsocketfd, BINDFD, CONNECTFD; Charbuffer[4096]; structsockaddr_in serveraddress; intSendsize, Recvsize; //printf ("================== Create Socket ======================\n"); //Create socketSOCKETFD = socket (af_inet, Sock_stream,0); if(Socketfd = =-1) {printf ("Create Socket error:%s (errno:%d) \ n", Strerror (errno), errno); Exit (0); }    //printf ("================== set address ========================\n"); //Set server addressmemset (&serveraddress,0,sizeof(serveraddress)); Serveraddress.sin_family=af_inet; Serveraddress.sin_port= Htons ( -); //serverAddress.sin_addr.s_addr = htonl (127.0.0.1);Inet_pton (Af_inet,"127.0.0.1", &serveraddress.sin_addr); Std::cout<< serverAddress.sin_addr.s_addr <<'\ n'; //printf ("================== bind address ========================\n"); //bind address to the socketBINDFD = Bind (Socketfd, (structsockaddr*) &serveraddress,sizeof(serveraddress)); if(BINDFD = =-1) {printf ("bind socket error:%s (errno:%d) \ n", Strerror (errno), errno); Exit (0); }    //printf ("================== listen ========================\n");    if(Listen (SOCKETFD,Ten) == -1) {printf ("Listen socket error:%s (errno:%d) \ n", Strerror (errno), errno); Exit (0); } printf ("================== waiting Connect ========================\n");  while(1) {Sleep (2); //recvive a connect and acceptCONNECTFD = Accept (SOCKETFD, (structsockaddr*) NULL, and NULL); if(Connectfd = =-1) {printf ("connet Socket error:%s (errno:%d) \ n", Strerror (errno), errno); Continue; }        //Receive DataRecvsize = recv (connectfd, buffer,4096,0); if(Recvsize = =-1) {printf ("recvive Data error:%s (errno:%d) \ n", Strerror (errno), errno); Continue; } printf ("%s\n", buffer); //Send DataSendsize = Send (connectfd, buffer,4096,0); if(Sendsize = =-1) {printf ("Send data error:%s (errno:%d) \ n", Strerror (errno), errno); Continue;    } close (CONNECTFD); } close (SOCKETFD);}

2. Client code:

#include <stdio.h>#include<stdlib.h>#include<string.h>#include<errno.h>#include<sys/types.h>//Basic System data type, the header file of the system's basic system data type#include <sys/socket.h>#include<netinet/inch.h>//Internet address Family#include <arpa/inet.h>//IP Address conversion function Inet_pton#include <unistd.h>//Close#include<iostream>intMain () {intSocketfd, CONNECTFD; intSendsize, Recvsize; structsockaddr_in serveraddress; Charsendbuf[4096]; Charrecvbuf[4096]; printf ("================== Create socket ========================\n"); SOCKETFD= Socket (Af_inet, Sock_stream,0); if(Socketfd = =-1) {printf ("Create socket error:%s (error%d) \ n", Strerror (errno), errno); Exit (0); } memset (&serveraddress,0,sizeof(serveraddress)); Serveraddress.sin_family=af_inet; Serveraddress.sin_port= Htons ( -); //serverAddress.sin_addr.s_addr = htonl ("127.0.0.1"); Inet_pton (Af_inet,"127.0.0.1", &serveraddress.sin_addr); Std::cout<< serverAddress.sin_addr.s_addr <<'\ n'; CONNECTFD= Connect (SOCKETFD, (structsockaddr*) &serveraddress,sizeof(serveraddress)); if(Connectfd = =-1) {printf ("Connect Server error:%s (Error (%d)) \ n", Strerror (errno), errno); Exit (0); } printf ("Send message to server:\n"); //std::cin >> sendbuf;Fgets (SendBuf,4096, stdin); //printf ("%s\n", sendbuf);Sendsize = Send (Socketfd, SendBuf, strlen (SENDBUF),0); if(Sendsize = =-1) {printf ("Send data error:%s (error%d) \ n", Strerror (errno), errno); Exit (0); } printf ("wait echo from server:\n"); Sleep (2); Recvsize= Recv (SOCKETFD, Recvbuf,sizeof(RECVBUF),0); if(Recvsize <0) {printf ("recvive Echo error:%s (error%d) \ n", Strerror (errno), errno); Exit (0); } printf ("%s", RECVBUF); Close (SOCKETFD);}

Several issues encountered in this process:

1, (client) errno 111:connection refused

This problem indicates that the client did not find the port that should be connected and needed to:

    • Ensure the service side listens on the corresponding port;
    • Turn off the firewall (Ubuntu commands below: sudo ufw disable);
    • and server side to Sudo run;

This problem occurs because my client and server port numbers do not match

2, (server) errno 14:bad address

The second parameter of the Accept () function refers to a buffer that receives the returned result, indicating the address of the client for this connection, and if it doesn't matter if the client address can be written as null, and once a non-null value is assigned to the parameter, the buffer will appear bad Address error

3, (server) errno 107:transport endpoint is not connected.

This problem is caused by the local socket descriptor written by my server-side recv and the first parameter of the Send function, in fact, this should be a connected socket descriptor

Network Programming Learning NOTE: Socket programming under Linux

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.