1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #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 6666 int main(void) { int sock; sock = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(SERVER_PORT); bind(sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
listen(sock, 128); printf("等待客户连接...\n");
while(1) { struct sockaddr_in client; int client_sock ; char client_ip[64]; char buf[256]; int buf_len; socklen_t client_addr_len = sizeof(client);
client_sock = accept(sock, (struct sockaddr *)&client, &client_addr_len); printf("client ip: %s\n port: %d\n", inet_ntop(AF_INET, &client.sin_addr.s_addr, client_ip, sizeof(client_ip)), ntohs(client.sin_port)); buf_len = read(client_sock, buf, sizeof(buf) - 1); buf[buf_len] = '\x00'; printf("接受到消息: %s\n", buf); for(int i = 0; i < buf_len; i++) { buf[i] = toupper(buf[i]); } write(client_sock, buf, strlen(buf)); printf("write[%s] finished!!!\n", buf);
close(client_sock); }
return 0; }
|