【C言語】【unix c】TCPトランスポート層に基づくプログラミングモデル
、 TCP
:
, , , LINUX , , 。 ( )-> , 。 ip, 。 ip , ip -> , -> , , 。-> -> , , 。
:
1、 ( )( , )
socket(2)
#include /* See NOTES */
#include
int socket(int domain, int type, int protocol);
:( ) 。
:
domain:
AF_INET: IPV4
AF_INET6: IPV6
type:
SOCK_STREAM: , , , TCP
SOCK_DGRAM: , UDP
protocol: 。 Internet 0
0
:
-1 errno
2、 ip ,
bind(2)
#include /* See NOTES */
#include
int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
:( ) , socket ,socket , , socket
:
sockfd: socket, socket
addr: , socket
addrlen: addr ,
:0
-1 errno
3、 , , ( )
listen(2)
#include /* See NOTES */
#include
int listen(int sockfd, int backlog);
:( , ( )) scoket , socket , , , accept
:
sockfd: socket
backlog:
:0
-1 errno
4、 , , ( c_fd)( , )
accept(2)
#include /* See NOTES */
#include
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
: socket ,
:
sockfd: socket
addr: , NULL addrlen NULL
addrlen: addr
: ,
-1 errno
5、 c_fd
a、
read(2)
b、
write(2)
c、
6、 c_fd,
close(2)
:
1、 ( )
socket(2)
2、 ( IP )
connect(2)
#include /* See NOTES */
#include
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
: socket
:
sockfd: socket, socket addr
addr: , ( )
addrlen: addr
:0
-1 errno
3、
4、
5、
6、 ,
:
1、
2、 :( , )
struct sockaddr {
sa_family_t sa_family; // , AF_XXX , AF_INET, TCP/IP
char sa_data[14];//14 , , , sockaddr , sockaddr_in
}
3、 sockaddr 【man in.h】 , IPV4,IPV6
#include
in_port_t:uint16_t
in_addr_t:uint32_t /
IPV4 :
struct sockaddr_in{
sa_family_t sin_family //AF_INET. , AF_INET
in_port_t sin_port //Port number. ( )
struct in_addr sin_addr //IP address. ip ( in_addr )
}
sockaddr_in sockaddr , sockaddr_in sockaddr , 。 sockaddr_in , (struct sockaddr*)mycket
sa_family_t
in_addr :
struct in_addr{
in_addr_t s_addr;
}
ip :
INADDR_ANY :IPV4 local host address , 。
4、 0~65535
5000 ,
5、 :
#include
uint32_t htonl(uint32_t hostlong);//
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
h:host
n:net
s:short
l:long
t:to
6、ip
inet_pton(3)
#include
int inet_pton(int af, const char *src, void *dst);
: (ipv4 ipv6 )
:
af:
AF_INET:ipv4
AF_INET6:ipv6
src: ip
dst:
:1
0 src
-1 errno
INET_NTOP(3)
#include
const char *inet_ntop(int af, const void *src,char *dst, socklen_t size);
:
:
af:
AF_INET:ipv4
AF_INET6:ipv6
src: struct in_addr
dst:
size:
: , dst ,
NULL errno
127.0.0.1: , ,
setsockopt()