服务端:
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdint.h>
#include <assert.h>
#include <fcntl.h>
#include <string.h>
#include <bits/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h> const char* ip = "192.168.16.105";
uint16_t port = ;
char buff[]; void make_sock_noblocking(int sock_fd)
{
int flags = fcntl(sock_fd, F_GETFL, );
flags |= O_NONBLOCK;
fcntl(sock_fd, F_SETFL, flags);
} int main()
{
int listen_fd = socket(PF_INET, SOCK_STREAM, ); struct sockaddr_in sock_addr;
memset(&sock_addr, , sizeof(sock_addr));
sock_addr.sin_family = AF_INET;
sock_addr.sin_port = htons(port);
inet_pton(AF_INET, ip, &(sock_addr.sin_addr)); int optval = ;
setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int)); int ret = bind(listen_fd, (sockaddr*)&sock_addr, sizeof(sock_addr)); listen(listen_fd, ); //make_sock_noblocking(listen_fd); struct sockaddr_in client_addr;
memset(&sock_addr, , sizeof(client_addr));
socklen_t len = sizeof(client_addr);
int conn_fd = accept(listen_fd, (sockaddr*)&client_addr, &(len)); printf("%d--------%s\n", conn_fd, strerror(errno)); int read_bytes = read(conn_fd, buff, sizeof(buff)); printf("%d %s\n", read_bytes, strerror(errno)); close(listen_fd);
close(conn_fd); // RST // shutdown(conn_fd, SHUT_RDWR); // RST // shutdown(conn_fd, SHUT_WR); // 不会产生RST sleep();
//exit(0);
}
客户端:
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdint.h>
#include <assert.h>
#include <fcntl.h>
#include <string.h>
#include <bits/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h> const char* ip = "192.168.16.105";
uint16_t port = ;
const char* msg = "bitch!"; int main()
{
struct sigaction sa;
memset(&sa, '\0', sizeof(sa));
sa.sa_handler = SIG_IGN;
sa.sa_flags = ;
if (sigaction(SIGPIPE, &sa, NULL)) {
return ;
} int sock_fd = socket(PF_INET, SOCK_STREAM, ); struct sockaddr_in sock_addr;
memset(&sock_addr, , sizeof(sock_addr));
sock_addr.sin_family = AF_INET;
sock_addr.sin_port = htons(port);
inet_pton(AF_INET, ip, &(sock_addr.sin_addr)); int ret = connect(sock_fd, (sockaddr*)&sock_addr, sizeof(sock_addr)); if(ret < )
{
printf("%s\n", strerror(errno));
}
//
// struct linger my_linger;
// memset(&my_linger, 0, sizeof(my_linger));
// my_linger.l_onoff = 1;
// my_linger.l_linger = 0;
//
// setsockopt(sock_fd, SOL_SOCKET, SO_LINGER, &my_linger, sizeof(my_linger)); int write_bytes = write(sock_fd, msg, strlen(msg)); if (write_bytes > )
{
printf("%d----%s\n", write_bytes, strerror(errno));
} sleep(); write_bytes = write(sock_fd, msg, strlen(msg)); if (write_bytes > )
{
printf("%d----%s\n", write_bytes, strerror(errno));
}
sleep(); write_bytes = write(sock_fd, msg, strlen(msg)); printf("%d----%s\n", write_bytes, strerror(errno)); close(sock_fd); return ;
}
客户端向已经关闭连接(不是半关闭)的服务端发送报文会被响应一个RST