网络模型
七层模型
四层模型
TCP : 面向连接,可靠的,面向字节流,支持点对点通信。
UDP : 无连接,不可靠,面向数据报文,支持一对一,一对多,多对多。
通信原理
常用函数
# include <sys/socket.h>
int socket ( int domain, int type, int protocol) ;
struct sockaddr
{ sa_family_t sa_family; char sa_data[ 14 ] ;
} ;
# include <sys/un.h>
struct sockaddr_un
{ sa_family_t sun_family; char sun_path[ ] ;
} ;
# include <netinet/in.h>
struct sockaddr_in
{ sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr;
} ;
int bind ( int sockfd, const struct sockaddr * addr, socklen_t addrlen) ;
int listen ( int sockfd, int backlog) ;
int accept ( int sockfd, struct sockaddr * addr, socklen_t * addrlen) ;
int connect ( int sockfd, const struct sockaddr * addr, socklen_t addrlen) ;
例子
server
int server_run ( ) { pthread_mutex_init ( & lock, NULL ) ; list = slink_create ( ) ; file_read ( list) ;
sockfd = socket ( AF_INET, SOCK_STREAM, 0 ) ; if ( sockfd == - 1 ) { perror ( "socket" ) ; return - 1 ; }
struct sockaddr_in addr; addr. sin_family = AF_INET; addr. sin_port = htons ( PORT) ; addr. sin_addr. s_addr = inet_addr ( IP) ; socklen_t len = sizeof ( addr) ;
int ret = bind ( sockfd, ( const struct sockaddr * ) & addr, len) ; if ( ret == - 1 ) { perror ( "bind" ) ; return - 1 ; }
ret = listen ( sockfd, MAX) ; if ( ret == - 1 ) { perror ( "listen" ) ; return - 1 ; }
while ( 1 ) { signal ( SIGINT, myexit) ; struct sockaddr_in caddr = { } ; socklen_t clen = sizeof ( caddr) ; int cfd = accept ( sockfd, ( struct sockaddr * ) & caddr, & clen) ; if ( cfd == - 1 ) { perror ( "accept" ) ; return - 1 ; } pthread_t id; int ret = pthread_create ( & id, NULL , run, ( void * ) & cfd) ; assert ( ret == 0 ) ; ret = pthread_detach ( id) ; assert ( ret == 0 ) ; }
}
client
int client_run ( ) {
int sockfd = socket ( AF_INET, SOCK_STREAM, 0 ) ; if ( sockfd == - 1 ) { perror ( "socket" ) ; return - 1 ; }
struct sockaddr_in addr = { } ; addr. sin_family = AF_INET; addr. sin_port = htons ( PORT) ; addr. sin_addr. s_addr = inet_addr ( IP) ; socklen_t len = sizeof ( addr) ;
int ret = connect ( sockfd, ( const struct sockaddr * ) & addr, len) ; if ( ret == - 1 ) { perror ( "connect" ) ; return - 1 ; }
}