參考資訊:
https://www.geeksforgeeks.org/socket-programming-cc/
server.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(int argc, char const* argv[]) { ssize_t r = 0; int opt = 1; int fd = -1; int new_socket = 0; char buf[1024] = {0}; struct sockaddr_in addr = {0}; const char *hello = "hello from server !"; if (argc != 3) { printf("usage: %s ip port\n", argv[0]); return 0; } socklen_t addrlen = sizeof(addr); fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { perror("socket"); return -1; } if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); return -1; } addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(argv[1]); // INADDR_ANY; addr.sin_port = htons(atoi(argv[2])); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); return -1; } if (listen(fd, 3) < 0) { perror("listen"); return -1; } new_socket = accept(fd, (struct sockaddr *)&addr, &addrlen); if (new_socket < 0) { perror("accept"); return -1; } r = read(new_socket, buf, sizeof(buf)); printf("%s\n", buf); send(new_socket, hello, strlen(hello), 0); close(new_socket); close(fd); return 0; }
client.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include <arpa/inet.h> int main(int argc, char const* argv[]) { int r = 0; int fd = -1; struct sockaddr_in addr = {0}; const char *hello = "hello from client !"; char buf[1024] = {0}; if (argc != 3) { printf("usage: %s ip port\n", argv[0]); return 0; } fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { perror("socket"); return -1; } addr.sin_family = AF_INET; addr.sin_port = htons(atoi(argv[2])); if (inet_pton(AF_INET, argv[1], &addr.sin_addr) <= 0) { perror("inet_pton"); return -1; } if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("connect"); return -1; } send(fd, hello, strlen(hello), 0); r = read(fd, buf, sizeof(buf)); printf("%s\n", buf); close(fd); return 0; }
編譯、執行
$ gcc server.c -o server $ gcc client.c -o client $ ./server 127.0.0.1 9999 & $ ./client 127.0.0.1 9999 hello from client ! hello from server !