Linux-socket Network sockets

Source: Internet
Author: User
Tags function prototype htons

OSI layer Seven Protocol features
TCP protocol Features

Reliable connection-oriented transmission
End-to-end, build/Disconnect
Correct and sequential data transfer
Agreement on issues
Loss, duplication, disorder, delay of IP datagrams
Matching of send and receive speeds
System restart, one party connection information is lost
Network congestion

UDP protocol Features

No connection
No need to establish a connection before communication
Do not use control messages
Low transfer overhead
Message oriented
Do not split messages, nor merge them
UDP packet size directly affects network utilization
Too small to cause a high header ratio
Too large to cause MTU fragmentation
Best effort, any interaction
Pair of one or one-to-many, many-to-one, and many-to-many

TCP/UDP port number as server program identity
When the server starts, the TCP/UDP port number that is used to register the local host first
The customer accesses a specific service by establishing a connection to the TCP port specified by the server (or sending information directly to the UDP port specified by the server)
When the host running the server program receives the information, it is forwarded to the server program that registered the port for processing

Network Hierarchy of Linux

BSD sockets are universal interfaces that support a variety of network work forms
INET socket support for Internet address families including TCP/IP protocol

Socket BASIC Concept

The socket interface is the interface between the application and the TCP/IP protocol stack
Define a set of functions/routines that support TCP/IP network application development
The system call associated with data communication is read ()/write ()
is a file descriptor
A socket describes one end of a communication connection
Two communication programs each have a socket to describe their own
Sockets are not part of the TCP/IP standard, but have become a de facto industry standard
UNIX Series systems provide sockets
Windows series, Macintosh series, Solaris, etc. also provide

形式(IP, PORT)网络进程标识<协议, 本地地址, 本地端口>网间通信标识<协议, 本地地址, 本地端口, 远程地址, 远程端口>端口分类公认端口:从0到1023小于256的端口作为保留端口注册端口:端口号从1024到49151 .动态和/或私有端口:从49152到65535。理论上,不应为服务分配这些端口。实际上,机器通常从1024起分配动态端口。
Basic Socket API
Socket()Create a new SOcketClose()Close a SOcketBind()The server(IP, Port)Give SOcketListen()Waiting for incoming customer connection requests(TCP)Accept()Accept client connection requests and establish connections(TCP)Connect()Making a connection request to the serverSend()/recv()Send/Receive Data
byte order ) different machines HBO is not the same as the CPU design about Motorola 68  K series, HBO and NBO the same Intel x86 series, HBO vs. NBO network byte order (nbo,network byte  order ) uses a uniform byte order to avoid compatibility issues before sending to the network: Convert to network byte order receive data from the network: Convert to host byte sequence header file Span class= "Hljs-preprocessor" > #include <netinet/in.h> function prototype uint32_t htonl (uint32_t hostlong); 32  bit values are converted from host byte order to network byte order uint16_t htons (uint16_t hostshort); 16 The  bit value is converted from host byte order to network byte order uint32_t Ntohl (uint32_t hostlong); converts 32  bit value from network byte order to host byte order uint16_t Ntohs (uint16_t hostshort); convert 16  bit value from network byte order to host byte order description H represents HOST,N representative networks representative Span class= "hljs-built_in" >short , L represents long  
Socket () function
功能创建一个套接字#include <sys/socket.h>函数原型int socket(intinttype, int protocol);参数说明domain:通信协议族,即地址族type:套接字类型protocol:通信协议常设置为0 ,由内核根据指定的类型和协议族使用默认的协议返回值成功时,返回一个大于等于0的文件描述符失败时,返回一个小于0的值
Linux supported protocols and address families
Address Protocol Protocol Description
Af_unix Pf_unix UNIX domain
Af_inet Pf_inet TCP/IP (V4)
Af_inet6 Pf_inet6 TCP/IP (V6)
af_ax25 pf_ax25 Amateur radio used by ax.25
Af_ipx Pf_ipx Novell's IPX
Af_appletalk Pf_appletalk AppleTalk DDS
Af_netrom Pf_netrom Amateur radio used by Netrom
Socket type
流套接字(SOCK_STREAM)可靠的、面向连接的通信使用TCP协议数据报套接字(SOCK_DGRAM)无连接服务使用UDP协议原始套接字(SOCK_RAW)允许对底层协议(如IP、ICMP)直接访问
int main(){    ……    int sockfd;    ifsocket0)) == -1) {          perror(“socketexit(1);     }     ……}
函数原型intgetsockopt(intintint*optval*optlen)intsetsockopt(intintint*optval*optlen)功能控制套接字行为,如修改缓冲区大小、传输方式等 参数说明level:指定控制套接字的层次SOL_SOCKET:通用套接字选项IPPROTO_IP:IP选项IPPROTO_TCP:TCP选项  optname:指定控制方式(选项名称)optval:获得/设置套接字选项值
Sol_socket parameter Options
So_broadcast allow broadcast data to be sentintSo_debug Allow debuggingintSo_dontroute do not find routesintSo_error Getting socket errorsintSo_keepalive Stay ConnectedintSo_linger Delay Closing the connectionstructLinger So_oobinline out-of-band data into normal data streamsintSO_RCVBUF Receive buffer sizeintSo_sndbuf Send buffer sizeintSo_rcvlowat Receive buffer lower boundintSo_sndlowat Send buffer lower limitintSo_rcvtimeo Receive timeoutstructTimeval So_sndtimeo Send TimeoutstructTimeval SO_REUSERADDR allows reuse of local addresses and portsintSo_type Get Socket typeintSo_bsdcompat compatible with BSD systemsint 
Socket Options Example
Change the Send/Receive buffer size receive bufferintnrecvbuf= +*1024;//Set to +Ksetsockopt(s, Sol_socket, so_rcvbuf, (const void*)&nrecvbuf, sizeof (int)); Send bufferintnsendbuf= +*1024;//Set to +Ksetsockopt(s, Sol_socket, SO_SNDBUF, (const void*)&nsendbuf,sizeof (int)); Note For customers, the SO_RCVBUF option must beConnectBefore setting up for the server, the SO_RCVBUF option must beListenPre-set
Bind () function
 (), you do not need to use the function  #include <sys/socket.h>  function prototype int  bind  (int  sockfd, struct sockaddr *my_addr , Socklen _t addrlen); parameter description sockfd: Call socket  return file descriptor MY_ADDR: Save address information (IP address and port) Addrlen: set to sizeof (struct sockaddr) return value is successful, return 0  fails, return-1  
  #include <string.h>   #include <sys/types.h>  # Include <sys/socket.h>   #define MyPort 3490  int  main () {int  sockfd;        struct  sockaddr_in my_addr;        SOCKFD = socket (af_inet, sock_stream, 0 );        my_addr.sin_family = af_inet;        My_addr.sin_port = htons (MyPort);        MY_ADDR.SIN_ADDR.S_ADDR = inet_addr ( "132.241.5.10" ); Bind (SOCKFD, (struct  sockaddr*) &my_addr, sizeof              (struct  sockaddr)); ...}  
SOCKADDR structure Definition
功能保存socket信息结构struct sockaddr {    short  /* 地址族,AF_xxx */char sa_data[14];  /* 协议地址 */  }; 说明sa_family一般为AF_INET(表示TCP/IP)sa_data包含socket的IP地址和端口号/include/linux/socket.h
Another representation structure for functional sockaddrstructsockaddr_in { Short intsin_family;/ * Address family * /  unsigned  Short intSin_port;/ * Port number * /  structIN_ADDR sin_addr;/ * IP address * /  unsigned Charsin_zero[8];/* Fill 0, keep the length of the struct sockaddr */}; Description Sin_zero is used to populate the SOCKADDR_IN structure with thestructSOCKADDR, usable bzero () ormemset() function to place it0When sin_port =0, the system randomly selects an unused port number when sin_addr = Inaddr_any, the pointer that fills in the native IP address to sockaddr_in and the pointer to SOCKADDR can be converted to each other
Connect () function
#include <sys/socket.h>函数原型int  connect(int  sockfd,  conststructsizeof(struct sockaddr)返回值成功时,返回0失败时,返回-1
  #include <string.h>   #include <sys/types.h>  # Include <sys/socket.h>   #define DEST_IP "132.241.5.10"   #define Dest_port  int  Main () {int  sockfd;        struct  sockaddr_in dest_addr;         SOCKFD = socket (af_inet, sock_stream, 0 );         dest_addr.sin_family = af_inet;         Dest_addr.sin_port = htons (Dest_port);        DEST_ADDR.SIN_ADDR.S_ADDR = inet_addr (DEST_IP); Connect (SOCKFD, (struct  sockaddr*) &dest_addr, si Zeof  (struct  sockaddr));  

Linux-socket Network sockets

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.