#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define ERR_MSG(msg) \
do { \
fprintf(stderr, "line = %d", __LINE__); \
perror(msg); \
} while (0);
#define IP "192.168.0.112"
int main(int argc, char const* argv[])
{
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0) {
ERR_MSG("socket");
return -1;
}
printf("socket successful__%d__", __LINE__);
// 快速释放
int reuse = 1;
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
ERR_MSG("setsockopt error");
return -1;
}
printf("允许端口快速重用\n");
// 绑定
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(6366);
sin.sin_addr.s_addr = inet_addr(IP);
if (bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
ERR_MSG("bind");
return -1;
}
// 监听
if (listen(sfd, 128) < 0) {
ERR_MSG("listen");
return -1;
}
// 获取客户端信息
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
int cfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
if (cfd < 0) {
ERR_MSG("accept");
return -1;
}
// 获取客户端发送的内容
char buf[1024] = { 0 };
size_t ret = 0;
while (1) {
ret = recv(cfd, buf, sizeof(buf), 0);
if (ret < 0) {
ERR_MSG("ret");
return -1;
} else if (ret == 0) {
printf("客服端下线\n");
break;
}
// 发送
strcat(buf, "*_*");
if (send(cfd, buf, sizeof(buf), 0) < 0) {
ERR_MSG("send");
return -1;
}
}
close(sfd);
close(cfd);
return 0;
}
客户端
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define ERR_MSG(msg) \
do { \
fprintf(stderr, "line = %d", __LINE__); \
perror(msg); \
} while (0);
#define IP "192.168.0.112"
int main(int argc, char const* argv[])
{
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0) {
ERR_MSG("sfd");
return -1;
}
struct sockaddr_in ain;
ain.sin_family = AF_INET;
ain.sin_port = htons(6366);
ain.sin_addr.s_addr = inet_addr(IP);
socklen_t addrlen = sizeof(ain);
if (connect(sfd, (struct sockaddr*)&ain, addrlen) < 0) {
ERR_MSG("connect");
return -1;
}
printf("connect successful");
char buf[1024] = { 0 };
while (1) {
memset(buf, 0, sizeof(buf));
printf("请输入>>");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0';
if (send(sfd, buf, sizeof(buf), 0) < 0) {
ERR_MSG("send");
return -1;
}
// 接收服务器的回复
bzero(buf, sizeof(buf));
size_t ret = recv(sfd, buf, sizeof(buf), 0);
if (ret < 0) {
ERR_MSG("ret");
return -1;
} else if (ret == 0) {
printf("服务器下线\n");
return -1;
}
printf("%s\n", buf);
}
close(sfd);
return 0;
}