Network Programming: Socket Learning Note

中文版: http://today2tmr.com/2017/06/29/网络编程之socket学习笔记/

Due to I’m beginner in this field, I intend to understand rather than master it. So… the note will be facial and easy without exhaustive theory.

Basic Concepts

  • Generally, we use IP + port to identify a network service.
  • Sockets seem the two ends between a telephone calling. Once the telephone is connected with the other telephone, the communication starts.
  • There are three kinds of sockets, we discuss two of them:
    • SOCK_STREAM (TCP)
    • SOCK_DGRAM (UDP)

Comparison between TCP and UDP

  • SOCK_STREAM (TCP)
    • Connection oriented. High correctness, low efficiency.
    • There is one-to-one connection between server and client, which makes sure that data will arrive at the destination.
  • SOCK_DGRAM (UDP)
    • Without connection. Low correctness ( data may lose ), high efficiency.
    • It needs only one socket between server and client. Just like the express delivery, we can write the address to send anywhere.
    • Applications like video or voice calls are usually implemented by UDP for its high speed. The loss of data doesn’t matter sometimes.

Three-way Handshake and Four-way Handshake

They are connection building and closing in TCP.

Build Connection

  • [Shake 1] Socket A:”Hi,Socket B,there are data to send to you. Let’s build the connection.”
  • [Shake 2] Socket B:”OK,I’m prepared.”
  • [Shake 3] Socket A:”Thanks for accepting my request.”

note:

  • SYN:Synchronous,segment presents that there is new connection.
  • Seq:Sequence Number,mark the data package.
  • ACK:Acknowledge,segment presents the validity of the Seq.
  • Ack:Acknowledge Number,which is equal to Seq + 1.

Close Connection

  • [Shake 1] Socket A:”Tasks are done. I’d like to close the connection.”
  • [Shake 2] Socket B:”Please wait for a moment and I’m going to prepare.”
  • Wait for a moment……
  • [Shake 3] Socket B:”I’m ready. It’s OK to close the connection now.”
  • [Shake 4] Socket A:”OK. Thanks for collaboration.”

note:

  • FIN:Finish,segment presents the closure of the connection.
  • Seq:Sequence Number,mark the data package.
  • ACK:Acknowledge,segment presents the validity of the Seq.
  • Ack:Acknowledge Number,which is equal to Seq + 1.
  • Functions in TCP

Create Socket

Function Prototype

  • Linux:
    • int socket(int family, int type, int protocol);
  • Windows:
    • SOCKET socket(int family, int type, int protocol)

Parameters Explanation and Values

  • family: Address family, the type of IP address
    • AF_INET: IPv4 domain
    • AF_INET6: IPv6 domain
    • (part)
  • type: the methods how data transfer
    • SOCK_STREAM
    • SOCK_DGRAM
    • (part)
  • protocol: transfer protocol
    • 0: depends on type
    • IPPROTO_TCP: TCP
    • IPPROTO_UDP: UDP
    • (part)

note:

  • We can infer protocol according to family and type sometimes. In that case we can set protocol as 0.

Bind Socket

Function Prototype

  • Linux:
    • int bind(int sock, struct sockaddr *addr, socklen_t addrlen);
  • Windows:
    • int bind(SOCKET sock, const struct sockaddr *addr, int addrlen);

Parameters Explanation and Values

  • sock: return value of function socket
  • addr: pointer to a sockaddr struct value
  • addrlen: length of addr, which could be calculated by sizeof()

Return Value:

  • 0: success
  • -1: error occurred

note:

  • We usually create and assign a sockaddr_in (for IPv4, it is sockaddr_in6 for IPv6) struct value, and then convert it to a sockaddr struct value.

sockaddr struct


 

sockaddr_in struct


 

note:
  • in_addr_t is defined in header file <netinet/in.h>,which is equal to unsigned long. inet_addr() is used to convert string IP.
  • sin_port should be the result of htons().

sockaddr_in6 struct


 

Example

 

Connect the Server

Function Prototype

  • Linux:
    • int connect(int sock, struct sockaddr *serv_addr, socklen_t addrlen);
  • Windows:
    • int connect(SOCKET sock, const struct sockaddr *serv_addr, int addrlen);

Parameters Explanation

The same as bind().

Listen and Accept

Function Prototype

Listen:

  • Linux:
    • int listen(int sock, int backlog);
  • Windows:
    • int listen(SOCKET sock, int backlog);

Accept:

  • Linux:
    • int accept(int sock, struct sockaddr *addr, socklen_t *addrlen);
  • Windows:
    • SOCKET accept(SOCKET sock, struct sockaddr *addr, int *addrlen);

Parameters Explanation

  • sock/addr/addrlen: the same as above
  • backlog: the maximum number of connections the kernel should queue for this socket

listen() Return Value:

  • 0: success
  • -1: error occurred

accept() Return Value:

  • A new socket file descriptor.
  • -1: error occurred

note:

  • addr is for client, and sock is for server
  • we should use the new socket returned later

Receive and Send Data

Function Prototype

Send:

  • Linux:
    • ssize_t write(int fd, const void *buf, size_t nbytes);
  • Windows:
    • int send(SOCKET sock, const char *buf, int len, int flags);

Receive:

  • Linux:
    • ssize_t read(int fd, void *buf, size_t nbytes);
  • Windows:
    • int recv(SOCKET sock, char *buf, int len, int flags);

Parameters Explanation

  • fd: file descriptor, which is socket
  • buf: the address of data
  • nbytes/len: bytes of data
  • flags: 0/NULL generally

Send Return Value:

  • bytes written
  • -1: error occurred

Receive Return Value:

  • bytes received
  • 0: the other socket is closed
  • -1: error occurred

note:

  • ssize_t means signed size_t

Close Socket

Function Prototype

  • Linux:
    • close(int sock)
  • Windows:
    • closesocket(SOCKET sock)
  • Functions in UDP

The Same Part as TCP

  • Create socket
  • Bind socket
  • Close socket

Different Part from TCP

Receive

  • Linux:
    • ssize_t recvfrom(int sock, void *buf, size_t nbytes, int flags, struct sockadr *from, socklen_t *addrlen);
  • Windows:
    • int recvfrom(SOCKET sock, char *buf, int nbytes, int flags, const struct sockaddr *from, int *addrlen);

Send

  • Linux:
    • ssize_t sendto(int sock, void *buf, size_t nbytes, int flags, struct sockaddr *to, socklen_t addrlen);
  • Windows:
    • int sendto(SOCKET sock, const char *buf, int nbytes, int flags, const struct sockadr *to, int addrlen);

note:

  • There is no need of connection, i.e. no connect(), accept() and listen().

Difference of Programming between Windows and Linux

The order of the following differences are Windows and then Linux.

  • Header file: winsock.h/winsock2.h vs. sys/socket.h
  • Type of socket: SOCKET vs. int
  • Access function: recv()/send() vs. read()/write()
  • Close socket: closesocket() vs. close()

Others:

  • In Windows, PE_INET is the same as AF_INET, which is Protocol Family.
  • In Windows, it has to initialize DLL by WSAStartup.

About WSAStartup() (in Windows)

  • Load DLL: #pragma comment (lib, "ws2_32.lib")
  • Initialize DLL:
  • Stop DLL: WSACleanup();

Simple examples

Transfer Text Messages

http://c.biancheng.net/cpp/html/3039.html

Transfer Files

http://c.biancheng.net/cpp/html/3045.html

Study Materials

One Reply to “Network Programming: Socket Learning Note”

Leave a Reply

Your email address will not be published.