Linux网络编程入门 ---- 实现客户端与服务端通信
功能实现实现客户端向服务端传输字符串,服务端打印服务端的ip和端口号并将字符串逆序回传给客户端。测试环境:Linux 服务器 (或者搭建本地虚拟机两台,处于同一网段)也可以通过环回接口模拟服务端和客户端通信。功能测试服务端代码#include <stdlib.h>#include <stdio.h>#include <string.h>#include <
·
功能实现
实现客户端向服务端传输字符串,服务端打印服务端的ip和端口号并将字符串逆序回传给客户端。
测试环境:
Linux 服务器 (或者搭建本地虚拟机两台,处于同一网段)
也可以通过环回接口模拟服务端和客户端通信。
功能测试
服务端代码
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <ctype.h>
#define SERVER_PORT 888
void reverse(char* arr,int begin,int end)
{
if(begin >= end) return;
while(begin < end)
{
char tmp = arr[begin];
arr[begin] = arr[end];
arr[end] = tmp;
begin++,end--;
}
}
int main()
{
int sock = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server_addr;
memset(&server_addr,0,sizeof(server_addr));
server_addr.sin_family = AF_INET; //指定协议族
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//监听本地所有ip
server_addr.sin_port = htons(SERVER_PORT);//绑定端口号
//
bind(sock,(struct sockaddr*)&server_addr,sizeof(server_addr));
listen(sock,128);
printf("等待用户连接:\n");
while(1)
{
struct sockaddr_in client;
int client_sock;
socklen_t client_len = sizeof(client);
char client_ip[33];
// memset(&client,0,sizeof(client));
// memset(&server_addr,0,sizeof(server_addr));
client_sock = accept(sock,(struct sockaddr*)&client,&client_len);
printf("client ip :%s\n",inet_ntop(AF_INET,&client.sin_addr.s_addr,client_ip,sizeof(client_ip)));
printf("client port :%d\n",ntohs(client.sin_port));
char buf[256];
int len = read(client_sock,buf,sizeof(buf) - 1);
buf[len] = 0;
printf("%s\n",buf);
reverse(buf,0,len-1);
len = write(client_sock,buf,len);
close(client_sock);
}
}
客户端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SERVER_PORT 888
#define SERVER_IP "192.168.23.202"
int main(int argc, char *argv[]){
int sockfd;
char *message;
struct sockaddr_in servaddr;
int n;
char buf[64];
if(argc != 2){
fputs("input error\n", stderr);
exit(1);
}
message = argv[1];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&servaddr, '\0', sizeof(struct sockaddr_in));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, SERVER_IP, &servaddr.sin_addr);
servaddr.sin_port = htons(SERVER_PORT);
connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
write(sockfd, message, strlen(message));
n = read(sockfd, buf, sizeof(buf)-1);
if(n > 0){
buf[n]='\0';
printf("receive: %s\n", buf);
}else {
perror("error!!!");
}
printf("finished.\n");
close(sockfd);
return 0;
}
更多推荐
已为社区贡献1条内容
所有评论(0)