一个简单的Linux下原生socket的tcp程序及其修改,最初参考网上资料完成如下:
/* * tcpserver.c *Author:coder_xia * Description:a simple tcp server */ #include <sys/socket.h> #include <netinet/in.h> //sockaddr_in #include <arpa/inet.h> //inet_addr #include <unistd.h> //close #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFERSIZE 128 #define TCPPORT 8001 #define BACKLOG 5 //max connection number int main(void) { int server_sockfd, client_sockfd; int addr_len, result, recv_len, on = 1; struct sockaddr_in server_address; struct sockaddr_in client_address; char recvbuf[BUFFERSIZE]; //init address server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(TCPPORT); addr_len = sizeof(struct sockaddr_in); //new server socket server_sockfd = socket(AF_INET, SOCK_STREAM, 0); if (-1 == server_sockfd) { perror("socket"); exit(EXIT_FAILURE); } //Enable address reuse result = setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); //bind and listen result = bind(server_sockfd, (struct sockaddr*)&server_address, addr_len); if (-1 == result) { perror("bind"); close(server_sockfd); exit(EXIT_FAILURE); } result = listen(server_sockfd, BACKLOG); if (-1 == result) { perror("listen"); close(server_sockfd); exit(EXIT_FAILURE); } while (1) { memset(recvbuf, 0, BUFFERSIZE); printf("server is waiting\n"); //Accept a connection, accept will block here, //so ,there's no need to sleep in this loop like in udp client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_address, &addr_len); //recv message from client recvrecv_len = recv(client_sockfd, recvbuf, BUFFERSIZE, 0); if (-1 == recv_len) { //error while recv perror("recv"); close(client_sockfd); close(server_sockfd); exit(EXIT_FAILURE); } else if (0 == recv_len) { //peer closed the socket close(client_sockfd); close(server_sockfd); exit(EXIT_FAILURE); } printf("server receieve : %s\n", recvbuf); printf("server port : %d\n", ntohs(server_address.sin_port)); printf("client port : %d\n", ntohs(client_address.sin_port)); printf("client addr : %s\n", inet_ntoa(client_address.sin_addr)); //send to client via client_sockfd result = send(client_sockfd, recvbuf, recv_len, 0); if (-1 == result) { perror("send"); close(client_sockfd); close(server_sockfd); exit(EXIT_FAILURE); } } close(server_sockfd); return 0; }简单的Linux下原生socket的tcp程序及其修改
内容版权声明:除非注明,否则皆为本站原创文章。