都是最简单的用来记忆。
this is my 的git地址:https://github.com/yanjinyun/cLanguageTcpUdp
tcp最简单的服务器:
int main(int argc, const char *argv[]) { int listenfd, acceptfd; struct sockaddr_in sin, cin; socklen_t clen; char buf[1024]; signal(SIGCHLD, SIG_IGN); listenfd = socket(PF_INET, SOCK_STREAM, 0); sin.sin_family = PF_INET; sin.sin_port = htons(atoi(argv[2])); sin.sin_addr.s_addr = inet_addr(argv[1]); bind(listenfd, (struct sockaddr *)&sin, sizeof(sin)); listen(listenfd, 5); while(1) { clen = sizeof(cin); printf("listen ...... "); acceptfd = accept(listenfd, (struct sockaddr *)&cin, &clen); printf("client %s %d connect ", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port)); if(fork() == 0) { close(listenfd); while(1) { bzero(buf, sizeof(buf)); if(recv(acceptfd, buf, sizeof(buf), 0) == 0) { printf("client %s %d exit ", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port)); exit(0); } printf("recv(%s %d): %s ", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), buf); } } close(acceptfd); } return 0; }
tcp最简单的客户端:
int main(int argc, const char *argv[]) { int cfd = socket(PF_INET, SOCK_STREAM, 0); struct sockaddr_in cin; char buf[1024]; cin.sin_family = PF_INET; cin.sin_port = htons(atoi(argv[2])); cin.sin_addr.s_addr = inet_addr(argv[1]); connect(cfd, (struct sockaddr *)&cin, sizeof(cin)); printf("connect ip(%s) port(%s) server ok ", argv[1], argv[2]); if(fork() == 0) { while(1) { bzero(buf, sizeof(buf)); recv(cfd, buf, sizeof(buf), 0); printf("recv: %s ", buf); } } while(1) { fgets(buf, sizeof(buf), stdin); buf[strlen(buf)-1] = '