C语言实现最基本的回射服务器与客户端(服务器用TCP协议回射客户发来的消息)
话不多说,直接上干货,下面两个程序都是linux程序。
server.c完整代码:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(int argc, char* argv[], char* envp[])
{
char buf[1024] = {'\0'};
int listenfd, new;
struct sockaddr_in servaddr;
struct sockaddr_in peeraddr;
socklen_t peerlen = sizeof(peeraddr);
memset(&servaddr, 0, sizeof(servaddr));
if ((listenfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
printf("listenfd fail! \n");
return 1;
}
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5188);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if ((bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) < 0)
{
printf("bind fail! \n");
return 2;
}
if ((listen(listenfd, SOMAXCONN)) < 0)
{
printf("listen fail! \n");
return 3;
}
if ((new = accept(listenfd, (struct sockaddr*)&peeraddr, &peerlen)) < 0)
{
printf("accept fail! new: %d\n", new);
return 4;
}
while (1)
{
memset(buf, 0, sizeof(buf));
read(new, buf, sizeof(buf));
fputs(buf, stdout);
write(new, buf, strlen(buf));
}
close(new);
close(listenfd);
return 0;
}
client.c完整代码:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[], char* envp[])
{
char buf[1024] = {'\0'};
char bufa[1024] = {'\0'};
int sock;
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5188);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
printf("socket fail! \n");
if (connect(sock, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
printf("connect fail! \n");
while (fgets(buf, sizeof(buf), stdin))
{
memset(&bufa, 0, sizeof(bufa));
write(sock, buf, sizeof(buf));
read(sock, bufa, sizeof(bufa));
fputs(bufa, stdout);
}
close(sock);
return 0;
}