客户端代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
if (argc != 3) {
printf("Usage: %s <SERVER_IP> <SERVER_PORT>\n", argv[0]);
return -1;
}
// 1. 创建套接字
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == sock_fd) {
perror("创建套接字失败");
return -1;
}
// 2. 绑定服务器地址和端口
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
server.sin_addr.s_addr = inet_addr(argv[1]);
// 3. 发起连接
int con_ret = connect(sock_fd, (struct sockaddr *)&server, sizeof(server));
if (-1 == con_ret) {
perror("连接服务器失败");
close(sock_fd);
return -1;
}
printf("成功连接到服务器 %s:%s\n", argv[1], argv[2]);
// 4. 畅聊
char buf[100];
while (1) {
memset(buf, 0, sizeof(buf));
fgets(buf, sizeof(buf), stdin); // 从标准输入读取用户输入
send(sock_fd, buf, strlen(buf), 0); // 发送消息到服务器
if (strcmp(buf, "bye\n") == 0) {
break; // 如果输入 "bye",则退出聊天
}
}
close(sock_fd); // 关闭套接字
return 0;
}
2.服务器
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
if (argc != 3) {
printf("Usage: %s <IP> <PORT>\n", argv[0]);
return -1;
}
// 1. 创建套接字
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == sock_fd) {
perror("创建套接字失败");
return -1;
}
// 2. 绑定IP地址和端口
struct sockaddr_in serve;
serve.sin_family = AF_INET;
serve.sin_port = htons(atoi(argv[2]));
serve.sin_addr.s_addr = inet_addr(argv[1]);
int ret = bind(sock_fd, (struct sockaddr *)&serve, sizeof(serve));
if (-1 == ret) {
perror("绑定函数失败");
close(sock_fd);
return -1;
}
// 3. 监听端口
int listen_ret = listen(sock_fd, 5);
if (-1 == listen_ret) {
perror("监听失败");
close(sock_fd);
return -1;
}
printf("等待连接...\n");
while (1) {
// 4. 等待连接
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int acc_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &client_addr_len);
if (acc_fd == -1) {
perror("接受连接失败");
close(sock_fd);
return -1;
}
// 获取并显示客户端的IP地址和端口号
char client_ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
int client_port = ntohs(client_addr.sin_port);
printf("连接成功,客户端 IP: %s, 端口: %d\n", client_ip, client_port);
// 5. 接收并显示消息
char buf[100];
while (1) {
memset(buf, 0, sizeof(buf));
int recv_ret = recv(acc_fd, buf, sizeof(buf), 0);
if (recv_ret <= 0) {
printf("客户端 %s:%d 断开连接\n", client_ip, client_port);
break;
}
printf("客户端 %s:%d 发送: %s", client_ip, client_port, buf);
if (strcmp(buf, "bye\n") == 0) {
printf("客户端 %s:%d 断开连接\n", client_ip, client_port);
break;
}
}
close(acc_fd); // 关闭当前客户端连接
}
close(sock_fd);
return 0;
}