tcp_server.c
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <unistd.h> #define SOCK_PORT 49128
#define MAXLINE 80 int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cliaddr;
socklen_t cliaddr_len;
char buf[MAXLINE];
char str[INET_ADDRSTRLEN];
int i, n; if((sockfd = socket(AF_INET, SOCK_STREAM, )) < ) {
perror("socket");
exit();
} /*Construct sockaddr_in struct*/
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SOCK_PORT);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < ) {
perror("connect");
exit();
} if (listen(sockfd, ) < ) {
perror("listen");
exit();
} while () {
cliaddr_len = sizeof(cliaddr);
connfd = accept(sockfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
n = read(connfd, buf, MAXLINE);
printf("received from %s at PORT %d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str)),
ntohs(cliaddr.sin_port));
for (i = ; i < n; i++)
buf[i] = toupper(buf[i]);
write(connfd, buf, n);
close(connfd);
} close(sockfd);
return ;
}
tcp_client.c
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h> #define SERV_PORT 49128
#define MAXLINE 80 int main(int argc, char *argv[])
{ int sockfd, n;
struct sockaddr_in servaddr;
char *str;
char buf[MAXLINE]; if (argc != ) {
fputs("usage: ./client message\n", stderr);
exit();
}
str = argv[]; if ((sockfd = socket(AF_INET, SOCK_STREAM, )) < ) {
perror("socket");
exit();
} bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);
servaddr.sin_port = htons(SERV_PORT); connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); write(sockfd, str, strlen(str));
n = read(sockfd, buf, MAXLINE);
printf("Response from server:\n");
write(STDOUT_FILENO, buf, n);
close(sockfd);
return ;
}
运行:
Client:
./client app
Response from server:
APP
Server:
received from 127.0.0.1 at PORT 48041