socket的TCP通訊簡單例子
阿新 • • 發佈:2019-02-19
/* tcp客戶端程式,注意一定要修改addr的值和本機相同才能正常工作 */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #include <netinet/in.h> #include <stdlib.h> #include <errno.h> int main(void) { int sock; int server_len; struct sockaddr_in server_address; sock = socket(PF_INET, SOCK_STREAM, 0); //建立SOCKET server_address.sin_family = AF_INET; //指定通訊協議 server_address.sin_addr.s_addr = htonl(INADDR_ANY);//或是指定當前IP地址inet_addr("192.168.88.123"); server_address.sin_port = htons(12345); connect(sock,(struct sockaddr*)&server_address,sizeof(server_address)); char sendbuf[1024]={0}; char recvbuf[1024]={0}; while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL) { write(sock,sendbuf,sizeof(sendbuf)); read(sock,recvbuf,sizeof(recvbuf)); fputs(recvbuf,stdout); memset(sendbuf,0,sizeof(sendbuf)); memset(recvbuf,0,sizeof(recvbuf)); } close(sock); return 0; }
#include <stdio.h> #include <unistd.h> /* tcp伺服器程式 */ #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #include <netinet/in.h> #include <stdlib.h> #include <errno.h> int main(void) { int server_sockfd,client_sockfd; int server_len,client_len; struct sockaddr_in server_address,client_address; server_sockfd = socket(PF_INET, SOCK_STREAM, 0); //建立SOCKET server_address.sin_family = AF_INET; //指定通訊協議 server_address.sin_addr.s_addr = htonl(INADDR_ANY);//相當於0.0.0.0 server_address.sin_port = htons(12345); server_len = sizeof(server_address); bind(server_sockfd, (struct sockaddr *)&server_address, server_len); //繫結SOCKET物件 listen(server_sockfd, SOMAXCONN); printf("SOMAXCONN:%d\n",SOMAXCONN); client_len=sizeof(client_address); client_sockfd=accept(server_sockfd, (struct sockaddr *)&client_address, (socklen_t *)&client_len); char recvbuf[1024]; while(1) { memset(recvbuf,0,sizeof(recvbuf)); read(client_sockfd, recvbuf, sizeof(recvbuf)); fputs(recvbuf,stdout); write(client_sockfd,recvbuf,sizeof(recvbuf)); } close(server_sockfd); close(client_sockfd); return 0; }