demo有缺陷有待修改,后面会更新
server端代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define SERVER_PORT 8888
int main(void)
{
struct sockaddr_in server_addr={0};
struct sockaddr_in client_addr={0};
char ip_str[20]={0};
int sockfd,connfd;
int addrlen=sizeof(client_addr);
char recvbuf[512];
int ret;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
{
perror("socket error");
exit(EXIT_FAILURE);
}
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
server_addr.sin_port=htons(SERVER_PORT);
ret=bind(sockfd,(struct sockaddr *)&server_addr,sizeof(server_addr));
if(ret<0)
{
perror("bind error");
close(sockfd);
exit(EXIT_FAILURE);
}
ret=listen(sockfd,50);
if(ret<0)
{
perror("linsten error");
close(sockfd);
exit(EXIT_FAILURE);
}
connfd=accept(sockfd,(struct sockaddr *)&client_addr,&addrlen);
if(connfd<0)
{
perror("accept error");
close(sockfd);
exit(EXIT_FAILURE);
}
printf("have client connect\n");
inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,ip_str,sizeof(ip_str));
printf("client ip :%s\n",ip_str);
printf("client port:%d\n",client_addr.sin_port);
while(1)
{
memset(recvbuf,0,sizeof(recvbuf));
ret=read(connfd,recvbuf,sizeof(recvbuf));
if(ret<0)
{
perror("read error");
close(sockfd);
break;
}
printf("from client:%s\n",recvbuf);
if(strncmp("exit",recvbuf,4)==0)
{
printf("server exit...\n");
close(connfd);
break;
}
}
close(sockfd);
exit(EXIT_SUCCESS);
}
client端代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define SERVER_PORT 8888
#define SERVER_IP "192.168.71.10"
int main(void)
{
struct sockaddr_in server_addr={0};
char buf[512];
int sockfd;
int ret;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(0>sockfd)
{
perror("socket error");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port=htons(SERVER_PORT);
server_addr.sin_addr.s_addr=inet_addr(SERVER_IP);
// inet_pton(AF_INET,SERVER_IP,&server_addr.sin_addr);
ret=connect(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
if(ret<0)
{
perror("connect error");
close(sockfd);
exit(EXIT_FAILURE);
}
printf("connect success\n\n");
while(1)
{
memset(buf,0,sizeof(buf));
printf("Please enter a string:");
scanf("%s",buf);
ret=write(sockfd,buf,sizeof(buf));
if(ret<0)
{
perror("write error");
break;
}
if(strncmp(buf,"exit",4)==0)
break;
}
close(sockfd);
exit(EXIT_SUCCESS);
}