上篇:
https://blog.csdn.net/m0_46480482/article/details/122995226
完整代码:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<ctype.h>
#include<arpa/inet.h>#define SERVER_PORT 666int main(void)
{int sock;// represent mailboxstruct sockaddr_in server_addr;// tag//create mailboxsock = socket(AF_INET,SOCK_STREAM,0);//1 clear tag first bzero(&server_addr,sizeof(server_addr));//2 set intnet protocol = IPV4server_addr.sin_family = AF_INET;//3 bind ip addr (all local addr)server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//4 set port numserver_addr.sin_port = htons(SERVER_PORT);// bind tag to mailboxbind(sock,(struct sockaddr *)&server_addr,sizeof(server_addr));// listening max 128 message at the same time listen(sock,128);printf("waiting for client link\n");int done=1;while(done){struct sockaddr_in client;int client_sock,len;char client_ip[64];char buf[256];socklen_t client_addr_len;client_addr_len = sizeof(client);client_sock = accept(sock,(struct sockaddr *)&client , &client_addr_len);printf("client ip:%s\t port: %d\n",inet_ntop(AF_INET,&client.sin_addr.s_addr,client_ip,sizeof(client_ip)),ntohs(client.sin_port));//read client server's datalen = read(client_sock,buf,sizeof(buf)-1);buf[len]='\0';printf("recive[%d]: %s\n",len,buf);// process messagefor(int i=0;i<len;i++){if(buf[i]>='a'&& buf[i]<='z')buf[i]-=32;}len = write(client_sock,buf,len);printf("len:%d\nsend_message:%s\nFinished.",len,buf);close(client_sock);done = 0 ;}close(sock);return 0;
}