Socket
一、Server
int server_fd,client_fd;
// 地址蔟、socket类型、通信协议
server_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server_fd < 0) {
printf("socket error
");
return -1;
}
struct sockaddr_in addr,clientAddr;
bzero(&addr,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(7787);
addr.sin_addr.s_addr = INADDR_ANY; // inet_addr("127.0.0.0")
// 地址绑定
bind(server_fd, (struct sockaddr_in *)&addr, sizeof(struct sockaddr_in));
// 100 最大连接数,监听连接请求--监听队列长度为 100
listen(server_fd, 100);
// 阻塞,直到有客户端连接
int s_size = sizeof(struct sockaddr_in);
client_fd = accept(server_fd, (struct sockaddr_in *)&clientAddr, &s_size);
if (client_fd >= 0) {
printf("connect client:%s
",inet_ntoa(clientAddr.sin_addr));
}
二、Client
int fd;
// 网络层协议: 决定抵制类型(ipv4、ipv6)AF_INET AF_INET6
// socket类型:SOCK_STREAM SOCK_DGRAM
// 运输层协议: IPPROTO_TCP IPPROTO_UDP
fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd <= 0) {
perror("open socket error
");
return -1;
}
struct sockaddr_in addr;
bzero(&addr,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(8088);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
// connect 成功返回0
if (connect(fd, (struct sockaddr_in *)&addr, sizeof(addr)) < 0) {
perror("connect error
");
return -1;
}